简体   繁体   中英

C#: Define Class Variable, Default Value and Get Set Not Working?

I'm trying to do something like public decimal hp = 1000; { get; set; } public decimal hp = 1000; { get; set; } public decimal hp = 1000; { get; set; } but it's not working...

I do know the conventional way to do this would be to create 2 separated variables, one private and one public but is it possible to set a default value and get/set with the same variable? Without having to put the default value in the actual constructor function?

This isn't possible.

But it will be soon! Take a look here

Auto-Properties will get initializers in C# 6.0. The syntax will be very close to what you were getting at:

public string MyString { get; set; } = "Hello, World!";

There's a lot of other cool stuff to be implemented too!

Syntax U try in your question will be provided in C# 6

[ http://odetocode.com/blogs/scott/archive/2014/08/04/c-6-0-features-part-i-property-initializers.aspx]

But with a little difference:

public decimal hp { get; set; } = 1000;

No, it's not possible. Auto-properties can't be initialized inline.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM