2016-06-11 75 views
1

描述我的问题最简单的方法是使用示例代码。我知道这不会编译,但我需要一个类似的选项覆盖静态类成员和通过泛型访问

abstract class Foo 
{ 
protected abstract static ElementName {get;} 
} 
class Bar : Foo 
{ 
protected static override ElementName 
{ 
    get 
    { 
     return "bar"; 
    } 
} 
} 
class Baz<T> where T : Foo 
{ 
public string ElementName 
{ 
    get 
    { 
     return T.ElementName; 
    } 
} 
} 

素不相识

+0

可能的复制[?有没有办法来强制C#类来实现某些静态函数(HTTP://计算器。 com/questions/577749/is-a-way-to-force-ac-sharp-class-to-implement-certain-static-functions) –

回答

3

这不能在你所希望的方式来完成,但可以使用反射实现类似的东西。下面是一个例子,有两种解决方案,您的问题(更新)的

abstract class Foo 
{ 
    protected abstract string _ElementName { get; } 

    public static string GetElementName<T>() where T : Foo, new() 
    { 
     return typeof(T).GetProperty("_ElementName", BindingFlags.Instance | BindingFlags.NonPublic)? 
         .GetValue(new T()) as string; 
    } 

    public static string GetStaticElementName<T>() where T : Foo, new() 
    { 
     return typeof(T).GetProperty("ElementName", BindingFlags.Static | BindingFlags.NonPublic)? 
         .GetValue(null) as string; 
    } 
} 

class Bar : Foo 
{ 
    protected static string ElementName 
    { 
     get 
     { 
      return "StaticBar"; 
     } 
    } 

    protected override string _ElementName 
    { 
     get 
     { 
      return "Bar"; 
     } 
    } 
} 

class FooBar : Bar 
{ 
    protected static string ElementName 
    { 
     get 
     { 
      return "StaticFooBar"; 
     } 
    } 

    protected override string _ElementName 
    { 
     get 
     { 
      return "FooBar"; 
     } 
    } 
} 

class Baz<T> where T : Foo, new() 
{ 
    public string ElementName 
    { 
     get 
     { 
      return Foo.GetElementName<T>(); 
     } 
    } 

    public string StaticElementName 
    { 
     get 
     { 
      return Foo.GetStaticElementName<T>(); 
     } 
    } 
} 

... 

Console.WriteLine(new Baz<Bar>().ElementName); // Bar 
Console.WriteLine(new Baz<FooBar>().ElementName); // FooBar 
Console.WriteLine(new Baz<Bar>().StaticElementName); // StaticBar 
Console.WriteLine(new Baz<FooBar>().StaticElementName); // StaticFooBar 
+0

谢谢,那应该是解决方案。但GetProperty发现非值事件不处理 – R3turnz

+0

你是什么意思,你能举个例子吗? – NValchev

+0

如果调用GetProperty,但没有属性,它将返回null。 GetValue方法现在会引发一个NullReferenceException,是吗? – R3turnz