我在 .NET 中发现了一些与我预期的有点不同的东西。我粘贴的代码没有意义,但它是我拥有的一个复杂得多的函数的浓缩版。我实际上是在获取匿名类型信息作为参数(尚未创建匿名类型的实例),我需要创建该类型的列表,填充它,然后返回列表。现在,我找到了解决方案,但我想知道为什么方法 B 有效,但方法 A 无效。
方法一:
static void Main(string[] args)
{
var newItem = new { ID = Guid.NewGuid(), Name = "Test" };
dynamic list;
list = Activator.CreateInstance(typeof(List<>).MakeGenericType(newItem.GetType()));
list.Add(newItem);
list.Add(Activator.CreateInstance(newItem.GetType(), new object[] { Guid.NewGuid(), "Test 2" }));
}
方法二:
static void Main(string[] args)
{
var newItem = new { ID = Guid.NewGuid(), Name = "Test" };
System.Collections.IList list;
list = (System.Collections.IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(newItem.GetType()));
list.Add(newItem);
list.Add(Activator.CreateInstance(newItem.GetType(), new object[] { Guid.NewGuid(), "Test 2" }));
}
同样,我不是在寻找解决方案,只是好奇为什么方法 B 有效但方法 A 无效。
谢谢!
最佳答案
因为在您的方法 B 中,您使用的是显式 IList.Add(object)
它接受一个对象并尝试将其转换为您的匿名类型。在方法 A 中,您有一个 List<anonymous type>
并且您正在使用通用的 Add 方法并尝试添加一个对象,但是您得到了 RuntimeBinderException
因为它期待正确转换的类型。如果你没有使用 dynamic
你会看到编译器错误。使用明确的 IList.Add
,将方法 A 更改为
((IList)list).Add(
Activator.CreateInstance(newItem.GetType(),
new object[] { Guid.NewGuid(), "Test 2" }));
关于dynamic - 匿名类型列表和动态...混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4900329/