代码之家  ›  专栏  ›  技术社区  ›  Steve Cooper

获取静态泛型方法中的当前类型?

  •  7
  • Steve Cooper  · 技术社区  · 15 年前

    我有一门这样的抽象课;

    public abstract PropertyBase
    {
        public static System.Type GetMyType()
        {
          return !!!SOME MAGIC HERE!!!
        }
    }
    

    我想对它进行子类化,当我调用static getmytype()时,我想返回子类的类型。所以,如果我声明一个子类型;

    public class ConcreteProperty: PropertyBase {}
    

    当我打电话的时候

    var typeName = ConcreteProperty.GetMyType().Name;
    

    我希望将“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); }
        }
    }
    

    而我 几乎 有一个实现,但我无法完全从NameProperty类中获取所需的信息。)

    3 回复  |  直到 15 年前
        1
  •  6
  •   LBushkin    15 年前

    您可以使用泛型部分实现(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();
    
        2
  •  4
  •   Vilx-    15 年前

    子类化位将不起作用,因为静态方法绑定到类型。这是一个 类型的方法 不是实例的方法。子类型不包含基类型的静态方法,因为它们是不同的类型,并且静态方法绑定到基类型。尽管编译器可能允许您像通过派生类那样调用基类的静态方法,但实际上它将从基类调用该方法。这只是语法糖。出于同样的原因,您不能“重写”子类中的静态方法,因为这样做毫无意义。

        3
  •  0
  •   Manish Basantani    15 年前

    只是想知道为什么要这样做?

    var typeName = ConcreteProperty.GetMyType().Name;
    

    不管您在调用方法时如何知道类型,您也可以这样做。

       var typeName = typeof(ConcreteProperty).Name;
    

    为了防止需要这样做,可以使用“阴影”覆盖子类中基类的实现。

    public class ConcreteProperty : PropertyBase {
    
            public new static Type GetMyType {
               //provide a new implementation here
            }
        }