-3

如果它可以是任何东西并且没有限制,那么存储T在列表/字典(例如)中的等价物是什么?Dictionary<string, T>

我有一个形式的方法Method<T>(string someString)。在这种方法中,我需要保存字符串T以供以后使用。另一种方法(来自另一个 API)将使用字符串和 T。这将在稍后的 Task.Run 中发生(我认为这在这里无关紧要)。

在这个类定义中没有<T>,因为类本身不存储任何与T.

编辑:这是流程:

在我的代码中的某处:

public void MyMethod<T>(string someString) { ... }

稍后,如果满足某些条件,则在我的代码中的其他位置(不一定在 MyMethod 类中)

public void SomeMethodFromAnotherAPI<T>(string someString)

4

3 回答 3

1

你的意思是这样的:

Dictionary<string, Type> dict = new Dictionary<string, Type>();

public void Method<T>(string text)
{
    dict.Add(text, typeof(T));
}

public void Usage()
{
    Method<string>("string");
    Method<IList>("list");
    Method<Action>("action");
}
于 2013-07-27T21:10:48.757 回答
1
void TheirMethod<T>(string text) { }

void MyMethod<T>(string text)
{
    Action action = () => TheirMethod<T>(text);
    // you can now return the action,
    // construct a thread with it
    // add it to a List...
    var thread = new Thread(new ThreadStart(action));
    thread.Start();
}
于 2013-07-27T23:13:53.110 回答
0

我建议研究 C# 中的泛型。这就是 C# 处理模板的方式。

泛型简介。

您可能还试图简单地存储类型。此时您需要使用Type 类GetType方法或TypeOf关键字来获取类型。

于 2013-07-27T20:50:05.143 回答