다양한 변수의 참조를 사전에 해당 키와 함께 저장하는 방법을 찾고 있습니다. 그럼 그 열쇠로 사전을 통해 참조에 액세스하여 변수의 인스턴스를 수정하고 싶습니다. 참조를 저장하는 데 성공했지만 <object>
을 사용하려고했습니다. 사전이나 목록에는 Dictionary<string, ref int>
과 같은 것도 허용되지 않습니다. 다음 코드는 컴파일되지만 값으로 변수를 업데이트하는 것처럼 보입니다. 어떤 아이디어 또는 해결 방법? 여기 사전에있는 객체에 대한 참조 저장
class Test1
{
IDictionary<string, object> MyDict = new Dictionary<string, object>();
public void saveVar(string key, ref int v) //storing the ref to an int
{
MyDict.Add(key, v);
}
public void saveVar(string key, ref string s) //storing the ref to a string
{
MyDict.Add(key, s);
}
public void changeVar(string key) //changing any of them
{
if(MyDict.GetType() == typeof(int))
{
MyDict[key] = (int)MyDict[key] * 2;
}
if(MyDict.GetType() == typeof(string))
{
MyDict[key] = "Hello";
}
}
}
그리고 이것은 내가
Test1 t1 = new Test1();
int myInt = 3;
string myString = "defaultString";
Console.WriteLine(myInt); //returns "3"
Console.WriteLine(myString); //returns "defaultString"
t1.saveVar("key1", ref myInt);
t1.saveVar("key2", ref myString);
t1.changeVar("key1");
t1.changeVar("key2");
Console.WriteLine(myInt); //should return "6"
Console.WriteLine(myString); //should return "Hello"
: 당신이 무엇을 할 수 있는지
그러나,이 같은 것이, 단순히 참조 형의 값 유형을 포장입니까? – Max
문자열은 참조 유형이므로 참조에 대한 참조를 저장 하시겠습니까? –
그럴 수 없습니다. – SLaks