Dot-Net

泛型方法的返回類型

  • February 21, 2011

我有一個泛型方法,它返回泛型類型的對象。一些程式碼:

public static T Foo<T>(string value)
{
   if (typeof(T) == typeof(String))
       return value;

   if (typeof(T) == typeof(int))
       return Int32.Parse(value);

   // Do more stuff
}

我可以看到編譯器可能會抱怨這個(“無法將類型 ‘String’ 轉換為 ‘T’”),即使程式碼不應該在執行時導致任何邏輯錯誤。有什麼方法可以實現我想要的嗎?鑄造沒有幫助…

好吧,你可以這樣做:

public static T Foo<T>(string value)
{
   if (typeof(T) == typeof(String))
       return (T) (object) value;

   if (typeof(T) == typeof(int))
       return (T) (object) Int32.Parse(value);

   ...
}

這將涉及值類型的裝箱,但它會起作用。

您確定這最好作為單一方法完成,而不是(比如說)可以由不同轉換器實現的通用介面?

或者,您可能想要Dictionary<Type, Delegate>這樣的:

Dictionary<Type, Delegate> converters = new Dictionary<Type, Delegate>
{
   { typeof(string), new Func<string, string>(x => x) }
   { typeof(int), new Func<string, int>(x => int.Parse(x)) },
}

那麼你會像這樣使用它:

public static T Foo<T>(string value)
{
   Delegate converter;
   if (converters.TryGetValue(typeof(T), out converter))
   {
       // We know the delegate will really be of the right type
       var strongConverter = (Func<string, T>) converter;
       return strongConverter(value);
   }
   // Oops... no such converter. Throw exception or whatever
}

引用自:https://stackoverflow.com/questions/5065693