メソッドがメソッドからいくつかのジェネリック型のいずれかを返すようにする方法はありますか?たとえば、私は次のようにしています。
public static T ParseAttributeValue<T>(this XElement element, string attribute)
{
if(typeof(T) == typeof(Int32))
{
return Int32.Parse(element.Attribute(attribute).Value);
}
if(typeof(T) == typeof(Double))
{
return Double.Parse(element.Attribute(attribute).Value);
}
if(typeof(T) == typeof(String))
{
return element.Attribute(attribute).Value;
}
if(typeof(T) == typeof(ItemLookupType))
{
return Enum.Parse(typeof(T), element.Attribute(attribute).Value);
}
}
(これは非常に迅速なモックアップにすぎません。nullチェックなどでは、実稼働コードを大幅に徹底する必要があることを認識しています...)
しかし、コンパイラーはそれを気に入らず、Int32
暗黙的に変換できないと不平を言っていますT
(キャストでも機能しません)。理解できます。コンパイル時にはそれが何でT
あるかを知る方法はありませんが、私は事前にそれをチェックしています。とにかく私はこの仕事をすることができますか?