C#,快速泛型问题

4

我需要创建一个快速类,只有两个属性(left和top),然后将它们调用到一个集合中。

有没有一种快速的方法来创建类结构,而不必使用泛型来实际创建强类型类?

提前感谢。

更好的是,框架是否有内置类型可以仅使用整数值存储左、上、右、下坐标?


2
你有特别的原因避免创建一个类吗?这似乎是最直接和简单的方法,所以在不了解你的情况下很难推荐替代方案。 - VoteyDisciple
1
请检查我的更新,我知道这只需要2分钟,但我想提高我对.NET的整体了解,并找到最佳方法来做到这一点。 - JL.
5个回答

9
自动属性可以帮助快速完成此操作。
public class Position<T> where T: struct
{
  public T Top { get; set; }
  public T Left { get; set; }
}

或者您可能想要查看System.Drawing命名空间中的Point或Rectangle类。


谢谢,我会查看那个矩形类! - JL.
1
我真的不认为做这件事有任何意义。它应该是一个简单的类,具有Top/Left/Bottom/Right作为整数属性。 - SolutionYogi
4
你假设这个位置总是整数,但根据这个位置的用途,浮点数或小数也是可以接受的。 - NerdFury

6
我认为你正在寻找的是System.Drawing.Rectangle(注意它是一个结构体而不是类;在System.Windows.Shapes中有一个类,但那是不同的)。既然已经有了所需的类型,创建新的通用类型就没有意义了。请参考System.Drawing.Rectangle

你还可以获得一堆免费的东西。 - Matthew Whited
除了一个问题,这是否意味着需要将另一个DLL与软件包一起发布? - JL.

2

你这么做的原因是什么?为什么不直接创建类呢?

如果你真的需要推迟某些事情,可以创建一个接口:

public interface IMyDeferredClass
{
    int MethodReturningInt(int parameter);
    int IntegerProperty { get; set; }
    int this[int index] { get; }
    event EventHandler SomeEvent;
}

你可以编写代码针对IMyDefferedClass进行编程,但最终你需要一个类来实现该接口:

public class MyDeferredClass : IMyDeferredClass
{
    public int MethodReturningInt(int parameter)
    {
        return 0;
    }

    public int IntegerProperty
    {
        get { return 0; }
        set {  }
    }

    public int this[int index]
    {
        get { return 0; }
    }

    public event EventHandler SomeEvent;
}

1

在C# 3.0中,你需要使用反射。

这两个建议都可能会导致性能开销增加。

static void Main(string[] args)
{
    var obj = new { Name = "Matt" };
    var val = DoWork(obj); // val == "Matt"
}

static object DoWork(object input)
{
    /* 
       if you make another anonymous type that matches the structure above
       the compiler will reuse the generated class.  But you have no way to 
       cast between types.
    */
    var inputType = input.GetType();
    var pi = inputType.GetProperty("Name");
    var value = pi.GetValue(input, null);
    return value;
}

在C# 4.0中,您可以使用“dynamic”类型。
static object DoWork(dynamic input)
{
    return input.Name;
}

Jon Skeet 指出了一个有趣的黑客技巧。

static object DoWork(object input)
{
    var casted = input.Cast(new { Name = "" });
    return casted.Name;
}

public static class Tools
{
    public static T Cast<T>(this object target, T example)
    {
        return (T)target;
    }
}

1

不好意思。匿名类只能在同一个方法中使用,而不能使用Jon的一些可怕的黑客技巧。(请参见评论)


这并不是“完全”正确的... http://msmvps.com/blogs/jon_skeet/archive/2009/01/09/horrible-grotty-hack-returning-an-anonymous-type-instance.aspx - Jon Skeet
@Jon:这是一个很好的观点。虽然有些恶心,但它确实可行。 - Matthew Whited

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接