具有相同名称的 C# 静态类字段和参数
本文关键字:静态类 字段 参数 | 更新日期: 2024-10-26 08:07:40
由于this.name
无法像静态类中的方法参数那样访问同名字段,因此我正在寻找一种方法来做到这一点。
举个例子,我想这样做:
static class test
{
private static string aString;
public static void method(string aString)
{
// aString (field) = aString (parameter)
}
}
使用:
test.Astring = x;
即将其替换为类名,在这种情况下进行测试。
static class test
{
private static string Astring="static";
public static void method(string Astring)
{
string passedString = Astring; // will be the passed value
string staticField = test.Astring; // will be static
}
}
如果我们像test.method("Parameter");
这样调用该方法,则staticField
将具有值static
,passedString
将具有值Parameter
。
关键字
this
表示类的当前实例;static 无法通过实例访问字段,您应该使用该类 名称,用于访问静态字段。
注意 :- 但在命名变量时请小心。避免在同一类中使用相同的名称。最好像下面这样定义类
static class test
{
private static string StaticAstring="static";
public static void method(string passedAstring)
{
string staticField = StaticAstring; // will be static
string passedString = passedAstring; // will be the passed value
}
}