gpt4 book ai didi

c# - 如何知道类型参数是否是动态的?

转载 作者:行者123 更新时间:2023-11-30 16:20:38 24 4
gpt4 key购买 nike

似乎每次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();
}
}

产生:

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.

如何在泛型方法中判断类型参数是动态的还是普通对象?

最佳答案

不,你不能。动态在旁观者的眼中(意思是:编译器)。它作为动态实现。但是,您可以检查 IDynamicMetaObjectProvider:如果一个对象实现了它,则调用者可能正在谈论 dynamic。不幸的是,反射也在 dynamic 中起作用,但根本不会涉及 IDynamicMetaObjectProvider

关于c# - 如何知道类型参数是否是动态的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14014795/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com