我不能檢索ReturnName
私人設置,並返回空/空?
//
private string testName;
public string ReturnName
{
private set { testName = "MyName"; }
get { return testName; }
}
//
string i = data.ReturnName;
我不能檢索ReturnName
私人設置,並返回空/空?
//
private string testName;
public string ReturnName
{
private set { testName = "MyName"; }
get { return testName; }
}
//
string i = data.ReturnName;
的結果應該只是這樣做:
public string ReturnName
{
get { return "MyName"; }
}
//
string i = data.ReturnName;
你不需要設定,如果你只是返回一個硬編碼值。更重要的是,你得到這個錯誤的原因是因爲你可能永遠不會調用set。如果你想有一個默認值,那麼你應該做更多的東西是這樣的:
private string testName = "MyName";
public string ReturnName
{
private set { testName = value; }
get { return testName; }
}
//
string i = data.ReturnName;
你的代碼是永遠不落ReturnName
。
如果您從另一個班級撥打,ReturnName
始終爲空,因爲您無法從中設置值。返回MyName
的唯一時間是當您在同一個類上的屬性上設置任何值時,將返回的值爲MyName
。
考慮下面的例子,
public Class SampleClass
(
private string testName;
public string ReturnName
{
private set { testName = "MyName"; }
get { return testName; }
}
public void MethodName()
{
ReturnName = "hello";
Console.WriteLine(ReturnName);
}
)
public class Main
{
SampleClass _x = new SampleClass();
Console.WriteLine(_x.ReturnName); // will output EMPTY
_x.MethodName(); // will output MyName
}
我知道了,謝謝,現在是修復 –