似乎每次dynamic
被泛型方法的调用者使用时,实际使用的类型都是简单的object
. 例如,代码:
public static void Main()
{
Program.DoSomething<int>();
Program.DoSomething<object>();
Program.DoSomething<dynamic>();
Console.WriteLine("Press any key to continue...");
Console.ReadKey(true);
}
public static T DoSomething<T>() where T : new()
{
Console.WriteLine(
"The type is: {0}; equal to object: {1}.",
typeof(T).FullName,
typeof(T) == typeof(object));
dynamic result = new ExpandoObject();
result.Hello = "Hello";
result.Number = 123;
try
{
return (T)result;
}
catch (Exception)
{
Console.WriteLine("Can't cast dynamic to the generic type.");
return new T();
}
}
产生:
类型为:System.Int32;等于对象:假。
无法将动态转换为泛型类型。
类型为:System.Object;等于对象:真。
类型为:System.Object;等于对象:真。
在泛型方法中,如何确定类型参数是动态的还是普通对象?