我需要创建一个快速类,只有两个属性(left和top),然后将它们调用到一个集合中。
有没有一种快速的方法来创建类结构,而不必使用泛型来实际创建强类型类?
提前感谢。
更好的是,框架是否有内置类型可以仅使用整数值存储左、上、右、下坐标?
我需要创建一个快速类,只有两个属性(left和top),然后将它们调用到一个集合中。
有没有一种快速的方法来创建类结构,而不必使用泛型来实际创建强类型类?
提前感谢。
更好的是,框架是否有内置类型可以仅使用整数值存储左、上、右、下坐标?
public class Position<T> where T: struct
{
public T Top { get; set; }
public T Left { get; set; }
}
或者您可能想要查看System.Drawing命名空间中的Point或Rectangle类。
System.Drawing.Rectangle
。你这么做的原因是什么?为什么不直接创建类呢?
如果你真的需要推迟某些事情,可以创建一个接口:
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;
}
在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;
}
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;
}
}
不好意思。匿名类只能在同一个方法中使用,而不能使用Jon的一些可怕的黑客技巧。(请参见评论)