转换为通用类型在C# [英] Cast to generic type in C#
问题描述
我有一个字典来将某个类型映射到该类型的某个通用对象。例如:
I have a Dictionary to map a certain type to a certain generic object for that type. For example:
typeof(LoginMessage) maps to MessageProcessor<LoginMessage>
现在问题是在运行时从字典中检索此通用对象。
Now the problem is to retrieve this generic object at runtime from the Dictionary. Or to be more specific: To cast the retrieved object to the specific generic type.
我需要它来工作,像这样:
I need it to work something like this:
Type key = message.GetType();
MessageProcessor<key> processor = messageProcessors[key] as MessageProcessor<key>;
希望有一个简单的解决方案。
Hope there is a easy solution to this.
编辑:
我不想使用Ifs和开关。由于性能问题,我不能使用某种反射。
I do not want to use Ifs and switches. Due to performance issues I cannot use reflection of some sort either.
推荐答案
这对你有用吗?
interface IMessage
{
void Process(object source);
}
class LoginMessage : IMessage
{
public void Process(object source)
{
}
}
abstract class MessageProcessor
{
public abstract void ProcessMessage(object source, object type);
}
class MessageProcessor<T> : MessageProcessor where T: IMessage
{
public override void ProcessMessage(object source, object o)
{
if (!(o is T)) {
throw new NotImplementedException();
}
ProcessMessage(source, (T)o);
}
public void ProcessMessage(object source, T type)
{
type.Process(source);
}
}
class Program
{
static void Main(string[] args)
{
Dictionary<Type, MessageProcessor> messageProcessors = new Dictionary<Type, MessageProcessor>();
messageProcessors.Add(typeof(string), new MessageProcessor<LoginMessage>());
LoginMessage message = new LoginMessage();
Type key = message.GetType();
MessageProcessor processor = messageProcessors[key];
object source = null;
processor.ProcessMessage(source, message);
}
}
我唯一不确定的是它是否足够在你的情况下,它有一个抽象的MessageProcessor。
This gives you the correct object. The only thing I am not sure about is whether it is enough in your case to have it as an abstract MessageProcessor.
编辑:我添加了一个IMessage接口。实际的处理代码现在应该成为应该都实现这个接口的不同消息类的一部分。
I added an IMessage interface. The actual processing code should now become part of the different message classes that should all implement this interface.
这篇关于转换为通用类型在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!