我有一个像这样的抽象类;
public abstract PropertyBase
{
public static System.Type GetMyType()
{
return !!!SOME MAGIC HERE!!!
}
}
Run Code Online (Sandbox Code Playgroud)
我想将它子类化,当我调用静态GetMyType()时,我想返回子类的类型.所以,如果我宣布一个子类型;
public class ConcreteProperty: PropertyBase {}
Run Code Online (Sandbox Code Playgroud)
然后我打电话的时候
var typeName = ConcreteProperty.GetMyType().Name;
Run Code Online (Sandbox Code Playgroud)
我希望'typeName'设置为"ConcreteProperty".我怀疑没有办法做到这一点,但我很感兴趣,如果有人知道如何获得这些信息.
(我试图解决的特殊问题是WPF中依赖属性的冗长;我希望能够做到这样的事情;
class NamedObject : DependencyObject
{
// declare a name property as a type, not an instance.
private class NameProperty : PropertyBase<string, NamedObject> { }
// call static methods on the class to read the property
public string Name
{
get { return NameProperty.Get(this); }
set { NameProperty.Set(this, value); }
}
}
Run Code Online (Sandbox Code Playgroud)
我几乎有一个实现,但我无法从NameProperty类中获得所需的信息.)
您可以使用泛型部分实现(1级深度继承):
class PropertyBase<T>
{
public static Type GetMyType() { return typeof (T); }
}
// the base class is actually a generic specialized by the derived class type
class ConcreteProperty : PropertyBase<ConcreteProperty> { /* more code here */ }
// t == typeof(ConcreteProperty)
var t = ConcreteProperty.GetMyType();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1727 次 |
| 最近记录: |