如何知道type参数是否是动态的? [英] How to know if the type parameter is dynamic?
问题描述
似乎每次通用方法的调用者使用 dynamic
时,实际使用的类型都是一个简单的 object
.例如,代码:
It seems that every time dynamic
is used by the caller of a generic method, the type actually used is a simple object
. For example, the code:
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;等于对象:False.
无法将动态类型转换为泛型类型.
类型是:System.Object;等于对象:True.
类型是:System.Object;等于对象:True.
The type is: System.Int32; equal to object: False.
Can't cast dynamic to the generic type.
The type is: System.Object; equal to object: True.
The type is: System.Object; equal to object: True.
如何在泛型方法中确定类型参数是动态对象还是普通对象?
How is it possible to determine, within the generic method, whether the type parameter is dynamic or an ordinary object?
推荐答案
否,您不能.动态是情人眼中的一切(意思是:编译器).实现为动态.但是,您可以检查 IDynamicMetaObjectProvider
:如果某个对象实现了该功能,则调用方可能正在谈论 dynamic
.不幸的是,反射也可以在 dynamic
内部使用,但完全不会涉及 IDynamicMetaObjectProvider
.
No, you cannot. Dynamic is all in the eye of the beholder (meaning: the compiler). It is implemented as dynamic. You can, however, check for IDynamicMetaObjectProvider
: if an object implements that, the caller is probably talking about dynamic
. Unfortunately, reflection also works inside dynamic
, but will not involve IDynamicMetaObjectProvider
at all.
这篇关于如何知道type参数是否是动态的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!