将 C# 6.0 默认属性值转换为 C# 5.0
Convert C# 6.0 default propertyvalues to C# 5.0
public List<string> MembershipIds
{
get;
set;
} = new List<string>();
我得到了无效的令牌
"=" in class, struct or interface member declaration.
这是 C# 6 的特性。如何将其转换为 C# 5?
此功能称为属性的默认值,它的作用是将赋值部分插入构造函数 你的 class
.
将代码更改为以下代码可在 属性 的支持字段上执行相同的操作,而无需更改所有构造函数,并且它在 C# 5.0 上受支持:
private List<string> mMembershipIds = new List<string>();
public List<string> MembershipIds
{
get
{
return mMembershipIds;
}
set
{
mMembershipIds = value;
}
}
在保留自动 属性 的情况下没有简单的方法。
如果您不需要自动 属性,请将代码转换为使用私有变量和非自动 属性:
private List<string> membershipIds = new List<string>();
public List<string> MembershipIds {
get { return membershipIds; }
set { membershipIds = value; }
}
如果确实需要自动属性,则需要在构造函数中进行赋值:
public List<string> MembershipIds { get;set; }
...
// This constructor will do the assignment.
// If you do not plan to publish no-argument constructor,
// it's OK to make it private.
public MyClass() {
MembershipIds = new List<string>();
}
// All other constructors will call the no-arg constructor
public MyClass(int arg) : this() {// Call the no-arg constructor
.. // do other things
}
public MyClass(string arg) : this() {// Call the no-arg constructor
.. // do other things
}
public List<string> MembershipIds
{
get;
set;
} = new List<string>();
我得到了无效的令牌
"=" in class, struct or interface member declaration.
这是 C# 6 的特性。如何将其转换为 C# 5?
此功能称为属性的默认值,它的作用是将赋值部分插入构造函数 你的 class
.
将代码更改为以下代码可在 属性 的支持字段上执行相同的操作,而无需更改所有构造函数,并且它在 C# 5.0 上受支持:
private List<string> mMembershipIds = new List<string>();
public List<string> MembershipIds
{
get
{
return mMembershipIds;
}
set
{
mMembershipIds = value;
}
}
在保留自动 属性 的情况下没有简单的方法。
如果您不需要自动 属性,请将代码转换为使用私有变量和非自动 属性:
private List<string> membershipIds = new List<string>();
public List<string> MembershipIds {
get { return membershipIds; }
set { membershipIds = value; }
}
如果确实需要自动属性,则需要在构造函数中进行赋值:
public List<string> MembershipIds { get;set; }
...
// This constructor will do the assignment.
// If you do not plan to publish no-argument constructor,
// it's OK to make it private.
public MyClass() {
MembershipIds = new List<string>();
}
// All other constructors will call the no-arg constructor
public MyClass(int arg) : this() {// Call the no-arg constructor
.. // do other things
}
public MyClass(string arg) : this() {// Call the no-arg constructor
.. // do other things
}