给定
int foo = 1;
Type unboundType = typeof(List<>);
Type w = unboundType.MakeGenericType(typeof(int));
if (w == typeof(List<int>))
{
Console.WriteLine("Yes its a List<int>");
try
{
((List<int>)(object)w).Add(foo);
}
catch(InvalidCastException)
{
Console.WriteLine("No you can't cast Type");
}
}
我可以验证该类型确实与构造类型匹配,并根据所述构造类型执行操作。但是,我无法使用 as
或显式强制转换将 Type
强制转换为它的 class
。是否有允许开发人员创建未绑定(bind)类型的 Type
的实际目的,或者此功能的存在是否只是为了以某种方式支持该语言?
最佳答案
并不是所有的事情都可以在编译时完成。有时,尤其是在库代码中,您需要接受所提供的内容。在只给定一个 object
或一个 Type
并且需要进行一些巧妙处理的情况下,未绑定(bind)类型会非常有用;例如:
object obj = NoIdeaWhatThisReturns();
IList list = (IList)Activator.CreateInstance(
typeof(List<>).MakeGenericType(obj.GetType()));
list.Add(obj);
基本上;使用大量反射或元编程的场景可能会发现自己在某些时候使用未绑定(bind)类型。
关于c# - 允许在 typeof 表达式中引用未绑定(bind)类型的效用是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14653729/