直到现在我才真正质疑过这个问题.我有一个包含许多字段的输入模型,我想通过输入模型显示属性的字符串名称,以便我的网格可以使用它们:
public class SomeGridRow
{
public string Code { get;set; }
public string Description { get;set; }
public const string Code = "Code";
}
Run Code Online (Sandbox Code Playgroud)
显然,这给出了错误:
'SomeGridRow'类型已经包含'Code'的定义
为什么CLR无法应对两个同名的属性,在我看来,这两个属性是分开的?
string code = gridRow.Code; // Actual member from instantiated class
string codeField = SomeGridRow.Code; // Static/Const
Run Code Online (Sandbox Code Playgroud)
我现在只是Fields在我的输入中使用一个子类,所以我可以使用SomeGridRow.Fields.Code.这有点乱,但它确实有效.
因为您也可以以相同的方式(在同一个类中)访问静态(或在这种情况下为非实例)属性,并且它会有点混乱,例如:
public class SomeGridRow
{
public string Code { get;set; }
public const string Code = "Code";
public void MyMethod() {
var thing = Code; //what would this reference?
}
}
Run Code Online (Sandbox Code Playgroud)
因为这两个:
public class SomeGridRow
{
public string Code { get;set; }
public void MyMethod() {
var thing = Code; //what would this reference?
}
}
Run Code Online (Sandbox Code Playgroud)
还有这个:
public class SomeGridRow
{
public const string Code = "Code";
public void MyMethod() {
var thing = Code; //what would this reference?
}
}
Run Code Online (Sandbox Code Playgroud)
是访问属性的有效方法,静态与否.它没有回答"为什么我不能?" 问题,但更多的是为什么它不被允许......这将是太模糊的IMO.