[英]C#, quick generics question
我需要創建一個只有2個屬性(左側和頂部)的快速類,然后我將在集合中調用它們。
是否有一種快速創建類結構的方法,而無需使用泛型實際創建強類型類本身?
提前致謝
更好的是,framwework是否具有內置類型,而不僅僅是以整數值存儲左,上,右,下坐標?
自動屬性有助於快速實現
public class Position<T> where T: struct
{
public T Top { get; set; }
public T Left { get; set; }
}
或者您可能想要查看System.Drawing命名空間中的Point或Rectangle類。
我認為你正在尋找System.Drawing.Rectangle
(這是一個結構,順便說一下不是類;在System.Windows.Shapes
有一個類,但那是不同的。)創建一個新的泛型類型時沒有意義你想要的已經在框架中了。
這樣做的原因是什么? 為什么不創建課程呢?
如果你真的需要推遲,你可以創建一個界面:
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;
}
不好意思 匿名類只能在相同的方法中使用,而不使用Jon的一些可怕的黑客。 (看評論)
在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中,您可以使用“動態”類型
static object DoWork(dynamic input)
{
return input.Name;
}
有趣的Hack由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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.