gpt4 book ai didi

C# - 如何将对象映射到适合该对象类型的泛型类?

转载 作者:太空宇宙 更新时间:2023-11-03 15:21:40 25 4
gpt4 key购买 nike

(我真的试着想出一个更好的标题,随意编辑)

假设我有一个通用的事件处理程序接口(interface)和实现:

public interface IEventHandler<T>
{
void HandleEvent(T t);
}

public class SlowButAccurateEventHandler<T> : IEventHandler<T>
{
// To emphasize that the implementation depends on T
private void SomeHelperClass<T> helperClass;

public void HandleEvent(T t) { ... }
}

public class FastEventHandler<T> : IEventHandler<T>
{
// To emphasize that the implementation depends on T
private void SomeHelperClass<T> helperClass;

public void HandleEvent(T t) { ... }
}

还有另一个类,我想保存 EventHandlers 的实例,但不能有泛型方法,因为它是 WCF 服务:

public class MyService : MyContract
{
// Pseudo (doesn't compile)
private Dictionary<Type, IEventHandler<T>> eventHandlers;

public MyService()
{
// More pseudo...
eventHandlers = new Dictionary<Type, IEventHandler<T>>()
{
{ typeof(string), new SlowButAccurateEventHandler<string>() },
{ typeof(int), new FastEventHandler<int>() },
};
}
public void RouteToEventHandler(object userEvent)
{
var handler = eventHandlers[typeof(userEvent))];
handler.HandleEvent(userEvent); // I realize that userEvent needs to be converted here
}
}

基本上,我有一些服务 (MyService),我想保留 IEventHandlers 并在某些事件到达时分派(dispatch)正确的处理程序。为此,我想保留一个字典,其中包含 CLR 类型和合适的 IEventHandler 之间的映射。这可能吗?

最佳答案

另一个实现,但是我会保留我之前的答案:

public interface IEventHandler
{
void HandleEvent(object value);
}

public interface IEventHandler<T> : IEventHandler
{
void HandleEvent(T value);
}

public abstract class EventHandler<T> : IEventHandler<T>
{
public void HandleEvent(object value)
{
if (value == null || !Type.Equals(value.GetType(), typeof(T)))
{
return;
}

HandleEvent(Convert(value));
}

private T Convert(object value)
{
try
{
return (T)value;
}
catch
{
return default(T);
}
}

public abstract void HandleEvent(T value);
}

public class FastEventHandler<T> : EventHandler<T>
{
public override void HandleEvent(T value)
{
throw new NotImplementedException();
}
}

在构造函数中,您可以初始化事件处理程序:

var handlers = new Dictionary<Type, IEventHandler>()
{
{ typeof(string), new FastEventHandler<string>() },
{ typeof(int), new FastEventHandler<int>() }
};

然后:

public void RouteToEventHandler(object userEvent)
{
if (userEvent == null)
{
return;
}

var handler = handlers[userEvent.GetType()];

handler.HandleEvent(userEvent);
}

关于C# - 如何将对象映射到适合该对象类型的泛型类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37101746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com