【发布时间】:2021-08-12 16:02:37
【问题描述】:
我目前正试图围绕 C# 的泛型展开思考,但我要么遗漏了一些信息,要么完全搞错了。我有一个名为 WatchedVariable 的类:
class WatchedVariable<T>
{
private T Data { get; set; }
public WatchedVariable(T initVal)
{
Data = initVal;
}
public T GetVal()
{
return Data;
}
public void SetData(T newVal)
{
Data = newVal;
}
}
这个类的重点是保存一个可以是任何类型的值,因为我不知道运行时该类型是什么。
我还有一个 DataStore 用于保存这些 WatchedVariable 对象的字典:
class DataStore
{
private Dictionary<string, WatchedVariable<T>> _store;
public DataStore()
{
_store = new Dictionary<string, WatchedVariable>();
}
public void AddToStore(string varname, WatchedVariable variable)
{
_store.Add(varname, variable);
}
public string GetFromStore(string key)
{
return _store[key].GetVal();
}
public void ChangeValInStore(string key, string newVal)
{
_store[key].SetData(newVal);
}
}
我的问题是如何设置 _store 字典,以便它可以获取这些通用 WatchedVariable 对象。目前编译器对我把 _store 字典值放在 WatchedVariable 旁边很生气。我想避免放置在 DataStore 类本身上,因为这实际上会将我锁定在一个特定的类型中,而我不想这样做。再说一次,要么我做错了,要么我在这里错过了一些东西。
【问题讨论】:
-
“避免放置”——放置什么?这个不清楚。
-
与 DataStore
中一样。我可以看到我的措辞在那里令人困惑。 -
我不知道运行时的类型是什么 - 这可能是它失败的地方 - 泛型不是运行时的东西。这是一种编写代码的方式,当您编写使用通用代码的其他代码时,编译器可以填充键入的缺失部分。微软写了
List<T>不知道你会在你的列表中添加什么类型的对象。你创建一个Person并创建一个List<Person>,编译器可以知道“哦,这个列表包含Person,这意味着public T GetThingAtIndex(int)方法应该返回一个Person。这不是将类型决策延迟到运行时的方法