2011-04-14 18 views
2

私は知っています、これはコードで最もよく説明されています。クラスのセットを考える:制約のあるジェネリックメソッドがある場合、ジェネリックパラメータの実際の型を渡す非ジェネリックメソッドを呼び出すことができます

public abstract class MyBaseType 
{ 
    public string Message { get; set; } 
} 

public class MySuperType : MyBaseType 
{ 
    public string AdditionalInfo { get; set; } 
} 

public class MyOtherSuperType : MyBaseType 
{ 
    public DateTime Started { get; set; } 
    public DateTime Finished { get; set; } 
} 

が渡され、その実際の型などのタイプではなく基本型を解釈しながら、ジェネリック型を渡す非ジェネリックメソッドを呼び出す一般的な方法を記述する方法はあります。 Tは基本型として解釈されるよう

public void OutputFormattedTypeInfo<T>(T theType) where T : MyBaseType 
{ 
    OutputFormattedTypeInfo(theType as T); 
} 

public void OutputFormattedTypeInfo(MySuperType theType) 
{ 
    System.Console.WriteLine(String.Format("{0} and {1}", theType.Message, theType.AdditionalInfo)); 
} 

public void OutputFormattedTypeInfo(MyOtherSuperType theType) 
{ 
    System.Console.WriteLine(String.Format("{0} - Start: {1}, End: {2}", theType.Message, theType.Started, theType.Finished)); 
} 

しかし、明らかにtheType:それは私がはこのような何かを書きたい、です。私はこのような反射を使うことができることを知っています:

Type type = typeof(MyBaseTypeDisplayFormatter); 
    MethodInfo method = type.GetMethod(
            "FormatSpecific", 
            BindingFlags.Instance | BindingFlags.NonPublic, 
            null, 
            new[] { update.GetType() }, 
            null); 

    return (MyBaseTypeDataItem)method.Invoke(this, new object[] { update }); 

しかし、それはちょっと気分が悪いです。より良い方法がありますか?

答えて

関連する問題