what is the automatic variable name of an auto-implemented properties
I'm trying to do this:
public string LangofUser
{
get
开发者_JAVA技巧 {
return string.IsNullOrEmpty("how to get value?") ? "English" : "how to get value?";
}
set;
}
do I have to do this?
string _LangofUser
public string LangofUser
{
get
{
return string.IsNullOrEmpty(_LangofUser) ? "English" : _LangofUser;
}
set { _LangofUser = value};
}
This mixing of auto-implement and not-auto-implemented properties in C# is not possible. A property must be fully auto-implemented or a normal property.
Note: Even with a fully auto-implemented property there is no way to reference the backing field from C# source in a strongly typed manner. It is possible via reflection but that's depending on implementation details of the compiler.
As others have said, don't try to mix automatic and regular properties. Just write a regular property.
If you want to know what secret names we generate behind the scenes for hidden compiler magic, see
Where to learn about VS debugger 'magic names'
but do not rely on that; it can change at any time at our whim.
If you provide your own implementation of the property, it's not automatic any more. So yes, you need to do create the instance.
Check this question What's the difference between encapsulating a private member as a property and defining a property without a private member?
If you want to keep the automatic property and still have a default value, why don't you initialize it in your constructor?
public class MyClass
{
public MyClass() { LangOfUser = "English"; }
public string LangOfUser { get; set; }
}
Since C# 6, you can also set a default value for a property as follows:
public class MyClass
{
public string LangOfUser { get; set; } = "English";
}
精彩评论