简体   繁体   中英

C#, quick generics question

I have a need to create a quick class with just 2 properties (left and top), I'll then call these in a collection.

Is there a quick way to create the class structure without having to actually create the strongly typed class itself using generics?

Thanks in advance

Better still, does the framwework have a built in type than can just store left, top, right, bottom co-ordinates in integer values?

Automatic Properties would help make this quick

public class Position<T> where T: struct
{
  public T Top { get; set; }
  public T Left { get; set; }
}

Or you might want to check out the Point or Rectangle classes in the System.Drawing namespace.

我认为你正在寻找System.Drawing.Rectangle (这是一个结构,顺便说一下不是类;在System.Windows.Shapes有一个类,但那是不同的。)创建一个新的泛型类型时没有意义你想要的已经在框架中了。

What's your reason for doing this? Why not just create the class?

If you really need to defer things, you can create an interface:

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

You can program to IMyDefferedClass, but you'll eventually need a class to implement that interface:

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;
}

No sorry. Anonymous classes can only be used in the same method without using some horible hack from Jon. (See comments)

in C# 3.0 you would need to use reflection.

Both of these suggestions can have substantial performance overhead.

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;
}

in C# 4.0 you could use the "dynamic" type

static object DoWork(dynamic input)
{
    return input.Name;
}

interesting Hack pointed out by 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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM