我正在尝试使用get()来设置文本值并访问它的简单操作。
场景:我正在研究Visual Studio中的框架。
private string saveValueName = "";
public string GetText()
{
return saveValueName;
}
public void SetText(string output)
{
DynamicValuesManager.Instance.SaveValue(saveValueName, output, true);
}
我的问题: 1.我需要保存我在SetText中的值,并在调用GetText()时在下一步中使用它。
您是否建议在此方案中使用getter / setter?
答案 0 :(得分:2)
这可以通过C#中的属性来完成。
df = structure(list(id = c(1L, 1L, 1L, 2L, 2L, 2L), result = c("a",
"b", "c", "e", "f", "g")), .Names = c("id", "result"),
class = "data.frame", row.names = c(NA, -6L))
现在您可以通过调用它来使用该属性,如下所示:
public string saveValueName { get; set; }
有关更多信息,请参阅此文章: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties#properties-overview
答案 1 :(得分:1)
private string saveValueName = string.empty; //better practice
public string GetText()
{
return saveValueName;
}
public void SetText(string output)
{
//save the incoming parameter to your private property:
saveValueName = output //this really should be called input since you are passing it in as a parameter but no biggie
//Not really sure what this function does?
DynamicValuesManager.Instance.SaveValue(saveValueName, output, true);
}
//Sample code to retrieve the value passed in:
tempVariable = yourClassName.GetText()
答案 2 :(得分:0)
使用它:
private string saveValueName = "";
public string GetText()
{
return this.saveValueName;
}
public void SetText(string output)
{
this.saveValueName = output;
}
还有另一种处理方法。它在C#中被称为属性。你可以这样做:
public string SaveValueName {get; set; }
通过这种方式,您可以轻松地为此设置值,而无需调用函数。例如,设置一个值你会这样做:
// obj is the object of the class
obj.SaveValueName = "some value here";
答案 3 :(得分:0)
疯狂猜测(基于DynamicValuesManager.Instance.SaveValue
调用):您可能正在寻找类似Dictionary
和indexer
的内容:
public class MyClass<T> {
private Dictionary<string, T> m_Values = new Dictionary<string, T>();
public T this[string name] {
get {
return m_Values[name];
}
set {
if (m_Values.ContainsKey(name))
m_Values[name] = value;
else
m_Values.Add(name, value);
}
}
}
...
var test = new MyClass<int>();
test["abc"] = 1;
test["x"] = 2;
test["pqr"] = 55;
Console.WriteLine(test["x"]);
甚至ExpandoObject
:
using System.Dynamic;
...
dynamic test = new ExpandoObject();
test.abc = 1;
test.x = 2;
test.pqr = 55;
Console.WriteLine(test.x);
答案 4 :(得分:0)
只是为了扩展Moher的答案。如果已经设置了变量,你就不应该写一个变量。
private string saveValueName = "";
public string GetText()
{
return this.saveValueName;
}
public void SetText(string output)
{
if (!string.Equals(output, saveValueName))
{
this.saveValueName = output;
}
}
如果您使用MVVM样式,则在设置变量时需要通知属性已更改。