有没有办法将参数传递给setter?我如何将字符串传递给下面的setter?如何使用新的字符串参数调用setter?
public string It
{
get{ { return it;}
set { it = value;}
}
Run Code Online (Sandbox Code Playgroud)
非常感谢你
Jon*_*eet 10
setter value根据您为属性赋值的值获取自己的"参数":
foo.It = "xyz"; // Within the setter, the "value" variable will be "xyz"
Run Code Online (Sandbox Code Playgroud)
如果要使用额外参数,则需要索引器:
public string this[string key]
{
get { /* Use key here */ }
set { /* Use key and value here */ }
}
Run Code Online (Sandbox Code Playgroud)
然后你可以访问它
foo["key"] = "newValue";
Run Code Online (Sandbox Code Playgroud)
您不能在C#中提供索引器名称,也不能按名称使用其他语言的命名索引器(COM的情况除外,从C#4开始).
编辑:正如Colin所指出的那样,你应该仔细使用索引器......不要只是将它们用作为setter获取额外参数的一种方法,然后你可以在getter中忽略它.像这样的东西会很糟糕:
// Bad code! Do not use!
private string fullName;
public string this[string firstName]
{
get { return fullName; }
set { fullName = firstName + " " + value; }
}
// Sample usage...
foo["Jon"] = "Skeet";
string name = foo["Bar"]; // name is now "Jon Skeet"
Run Code Online (Sandbox Code Playgroud)
您可以像为变量赋值一样对其进行赋值:
It = "My String";
Run Code Online (Sandbox Code Playgroud)
属性 getter/setter 只是string get_It()and的语法糖void set_It(string value)
| 归档时间: |
|
| 查看次数: |
13069 次 |
| 最近记录: |