防爆pression是一个值,因此不能作为赋值目标 [英] Expression Is a value and therefore cannot be the target of an assignment
问题描述
我跑进使用结构今天抓住我措手不及的问题,我希望有人能提供一些线索就可以了我。
I ran into an issue using a struct today that caught me off guard, and I was hoping someone could shed some light on it for me.
我有这样定义一个结构:
I have a struct defined like this:
public struct PaymentDetail
{
public Decimal Amount{get;set;}
public string CheckNumber{get;set;}
public PaymentType PaymentType{get;set;}
}
我有一个包含此信息的类
I have a class that contains this info
public class Transaction
{
public PaymentDetail Payment{get;}
}
我这,我想设置这样的基本属性presentation模型
I have a presentation model which in which I want to set the underlying properties like this
public class ViewModel
{
public Decimal Amount
{
get{return _Transaction.PaymentDetail.Amount;}
set
{
//This is the offending line of code
_Transaction.PaymentDetail.Amount = value;
RaisePropertyChanged("Amount");
}
}
}
什么是奇怪的是,我可以做这项工作,如果我在付款属性更改为公共领域是这样的:
What's wierd is I can make this work if I change the Payment property to a public field like this:
public class Transaction
{
public PaymentDetail Payment;
}
有obviosuly东西我不理解导致此结构。这是一个坏主意?有没有更好的办法?我究竟做错了什么?
there's obviosuly something I don't understand about structs that are causing this. Is this a bad idea? Is there a better way? What am I doing wrong?
推荐答案
第一 - 没有可变的结构体(即一个结构,你可以建成后,通过制定者等改变价值观,)。即混乱这里的首要原因。
First - don't have mutable structs (i.e. a struct where you can change the values after construction, via setters etc). That is the primary cause of confusion here.
问题的关键是,当你调用一个属性(如付款
)你(在您的本地栈区)的值的复制。一类,即基准(没有问题)的副本。对于一个结构它是结构本身的副本。任何更改该值将被丢弃,所以编译器已经从丢失数据拦你。
The point is; when you call a property (like Payment
) you get a copy of the value (in your local stack area). For a class, that is a copy of the reference (no problem). For a struct it is a copy of the struct itself. Any changes to that value will be discarded, so the compiler has stopped you from losing data.
当它是一个公共领域,你是直接变异的原始值,这就是为什么它不介意。但变异结构确实不是一个好主意。
When it is a public field, you are mutating the original value directly, which is why it doesn't mind. But mutating structs really isn't a good idea.
请 PaymentDetail
A类;这是正确的解决方案在这里...
Make PaymentDetail
a class; that is the correct solution here...
在.NET中,结构不是无物的行为 - 他们是价值类型。比如像货币/值对,时间范围,等等可能使有效的结构体 - 而不是 PaymentDetail
In .NET, structs aren't "objects without behaviour" - they are "value-types". Things like "a currency/value pair", "a time range", etc might make valid structs - but not PaymentDetail
.
这篇关于防爆pression是一个值,因此不能作为赋值目标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!