2016-06-11 3 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; 
    } 
} 
} 

Grettings

+0

の可能性のある重複した[は、特定の静的関数を実装するためにC#クラスを強制する方法はありますか?](のhttp://のstackoverflow。 com/questions/577749/is-there-a-way-to-force-ac-sharp-class-to-implement-特定の静的関数) –

答えて

3

を行うことができませんが、リフレクションを使用して似たような達成することができます同様のオプションが必要です。ここで(を更新)あなたの問題には、次の2つの可能なソリューションを提供する例です。

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

関連する問題