在自动实现的get中,C#支持字段背后的代码是什么;组;?

时间:2011-11-11 04:34:53

标签: c#

我正在学习它可能是这样的:

public string ModifiedBy {
      get { return m_ModifiedBy ?? string.Empty; }
      set { 
        if(value!=null) {
            m_ModifiedBy = value;
            m_Modified = DateTime.Now;       
        }
      }
    } 

这是正确的还是或多或少涉及?我想简单地复制一下get的内容;组;这是自动实施的。

4 个答案:

答案 0 :(得分:3)

这是错的;你的代码不仅仅是获取和设置一个字符串。

自动实现的字符串属性ModifiedBy只是扩展为以下等效的手动实现属性:

// Key difference: the backing field of an automatic property
// is not accessible by your own code
private string m_modifiedBy;

public string ModifiedBy {
    get { return m_modifiedBy; }
    set { m_modifiedBy = value; }
}

就是这样。没有非{* 1}}的默认值,没有涉及其他类成员,没有空检查,没有其他逻辑等。空值的处理方式与任何其他值完全相同。

答案 1 :(得分:1)

auto-implemented property的实现如下:

private int _foo;   // compiler-generated
public int Foo
{
    get { return _foo; }
    set { _foo = value; }
}

答案 2 :(得分:0)

自动实现的属性大部分都可以像以下示例一样工作

// This class is mutable. Its data can be modified from
// outside the class.
class Customer
{
    // Auto-Impl Properties for trivial get and set
    public double TotalPurchases { get; set; }
    public string Name { get; set; }
    public int CustomerID { get; set; }

    // Constructor
    public Customer(double purchases, string name, int ID)
    {
        TotalPurchases = purchases;
        Name = name;
        CustomerID = ID;
    }
    // Methods
    public string GetContactInfo() {return "ContactInfo";}
    public string GetTransactionHistory() {return "History";}

    // .. Additional methods, events, etc.
}


class Program
{

    static void Main()
    {
        // Intialize a new object.
        Customer cust1 = new Customer ( 4987.63, "Northwind",90108 );

        //Modify a property
        cust1.TotalPurchases += 499.99;

    }
}

在您的代码部分中,您不应检查null值,因为如果将null设置为属性,那么它将无效。

答案 3 :(得分:0)

您可以通过使用ILSpy对其进行反编译来查看编译器创建的实际代码。查看here以获取生成内容的示例。