此代码段出了什么问题?
class Program
{
static void Main(string[] args)
{
var obj = new { Name = "A", Price = 3.003 };
obj.Name = "asdasd";
obj.Price = 11.00;
Console.WriteLine("Name = {0}\nPrice = {1}", obj.Name, obj.Price);
Console.ReadLine();
}
}
我遇到以下错误:
Error 5 Property or indexer 'AnonymousType#1.Name' cannot be assigned to -- it is read only .....\CS_30_features.AnonymousTypes\Program.cs 65 13 CS_30_features.AnonymousTypes
Error 6 Property or indexer 'AnonymousType#1.Price' cannot be assigned to -- it is read only .....\CS_30_features.AnonymousTypes\Program.cs 66 13 CS_30_features.AnonymousTypes
如何将值重新设置为匿名类型对象?
C#中的匿名类型是不可变的,因此没有属性设置器方法。您需要使用以下值创建一个新的匿名类型:
obj = new { Name = "asdasd", Price = 11.00 };
使用匿名属性创建匿名类型。构建对象后,您将无法分配它们。
匿名类型提供了一种封装一组只读属性
[旧问题,但我自己也遇到了同样的问题。我最终使用了ExpandoObject。我相信自C#4起就已经存在。