Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
900 views
in Technique[技术] by (71.8m points)

.net - 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;}
}

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;
}

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

Make PaymentDetail a class; that is the correct solution here...

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...