爲什麼在擁有auto屬性的類中調用初始化程序時,使用對象初始值設定項來設置私有集自動屬性成爲可能?我列舉了兩個班。使用對象初始化器設置私有setter
public class MyClass
{
public string myName { get; private set; }
public string myId { get; set; }
public static MyClass GetSampleObject()
{
MyClass mc = new MyClass
{
myName = "Whatever", // <- works
myId = "1234"
};
return mc;
}
}
public class MyOtherClass
{
public static MyClass GetSampleObject()
{
MyClass mc = new MyClass
{
myName = "Whatever", // <- fails
myId = "1234"
};
return mc;
}
}
,因爲它在同一類範圍內 – Reniuz
爲什麼*不可能? –
@JonSkeet - OP可能會認爲'private'意味着在屬性範圍內? – Oded