C#泛型/一般类型

时间:2014-04-29 16:36:47

标签: c# generics types

static Dictionary<Type, Action<object>> handlers;

public static void Main (string[] args)
{
    handlers = new Dictionary<Type, Action<object>>();

    AddHandler<One>((object rawOne) => { One one = (One)rawOne; Console.WriteLine(one.Data); });
    AddHandler<Two>((object rawTwo) => { Two two = (Two)rawTwo; Console.WriteLine(two.Data); });

    Handle(new One("Test"));
    Handle(new Two(123));
}

public static void AddHandler<T>(Action<object> handler)
{
    handlers[typeof(T)] = handler;
}

public static void Handle(object data)
{
    handlers[data.GetType()].Invoke(data);
}

由于缺乏一个更好的方法来说明这一点:我如何以一种不必投射rawOne和rawTwo的方式来制作它?

基本上,我想要这个:

AddHandler<One>((object rawOne) => { One one = (One)rawOne; 
Console.WriteLine(one.Data); });

看起来像这样:

AddHandler<One>((One one) => { Console.WriteLine(one.Data); };

但是,我不知道如何实现这一目标。显然,我必须以某种方式修改字典,但我不知道如何。

1 个答案:

答案 0 :(得分:2)

像这样:

public static void AddHandler<T>(Action<T> handler)
{
    handlers[typeof(T)] = o => handler((T)o);
}

此外,由于编译器可以推断出您的类型的某些内容,您可以这样说:

AddHandler((One one) => { Console.WriteLine(one.Data); };

......或者这个:

AddHandler<One>(one => { Console.WriteLine(one.Data); };