C#的匿名类型不能被分配到 - 它是只读 [英] C# Anonymous types cannot be assigned to -- it is read only
本文介绍了C#的匿名类型不能被分配到 - 它是只读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么是错的这个代码片断?
What is wrong with this code-snippet?
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();
}
}
我收到以下错误:
I am getting the following errors:
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
如何重新设定值变成一个匿名类型的对象?
How to re-set values into an anonymous type object?
推荐答案
匿名类型在C#中是不可变的,因此不具有财产setter方法。你需要创建一个新的anonmyous类型的值
Anonymous types in C# are immutable and hence do not have property setter methods. You'll need to create a new anonmyous type with the values
obj = new { Name = "asdasd", Price = 11.00 };
这篇关于C#的匿名类型不能被分配到 - 它是只读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文