我在C#中的類型推斷中發現了一些奇怪的東西。C#類型推斷,泛型和接口
該示例。
我有一個接口
interface IInterface1
{
}
,並實現該接口
class Class1 : IInterface1
{
}
然後一類我有一個創建類
static Class1 GetInstanceOfClass1()
{
return new Class1();
}
而且我要的功能使用泛型函數將返回一個可枚舉的
static IEnumerable<T> GetSomething<T>() where T : IInterface1
{
yield return GetInstanceOfClass1();
}
完整的代碼
using System.Collections.Generic;
namespace TypeInference
{
interface IInterface1
{
}
class Class1 : IInterface1
{
}
class Program
{
static Class1 GetInstanceOfClass1()
{
return new Class1();
}
static IEnumerable<T> GetSomething<T>() where T : IInterface1
{
yield return GetInstanceOfClass1();
}
static void Main(string[] args)
{
}
}
}
此代碼不編譯
無法隱式轉換類型 'TypeInference.Class1' 到 'T'
如果我寫as
yield return (T)GetInstanceOfClass1();
該錯誤消息是
無法將類型 'TypeInference.Class1' 到 'T'
它不能像以前那樣進行轉換。
好的。我寫的
yield return (IInterface1)GetInstanceOfClass1();
,並得到
無法隱式轉換類型 'TypeInference.IInterface1' 到 'T'
它不能像以前那樣轉換。
但如果我寫的
yield return (T)(IInterface1)GetInstanceOfClass1();
一切正常。
有人可以解釋我什麼是錯的,爲什麼代碼最終編譯?
謝謝。
不保證'(T)(IInterface1)GetInstanceOfClass1();'不會在運行時中斷。可以創建'class NewClass1:IInterface1';調用'GetSomething()'並得到異常。編譯器*信任你當你做類型轉換'(T)(IInterface1)',但運行時不會 –
ASh