根据类型参数在通用方法中调用不同的方法 [英] Call different methods in a generic method based on the type parameter

查看:398
本文介绍了根据类型参数在通用方法中调用不同的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几种这样的方法:

public string GetStringValue(string field) { /* ... */ }
public int GetIntValue(string field) { /* ... */ }

现在,我想编写一个具有以下签名的通用方法:

Now I want to write a generic method which has the following signature:

public bool CopyValue<T>(string field, Action<T> copyAction)

根据类型参数,我想使用非泛型方法之一的返回值调用copyAction.我的第一次尝试是

Depending on the type parameter I want to invoke copyAction with the return value of one of the non-generic methods. My first try was

public bool CopyValue<T>(string field, Action<T> copyAction)
{
    if (typeof(T) == typeof(string))
        copyAction((GetStringValue(field));
    else if (typeof(T) == typof(int))
        copyAction(GetIntValue(field));
    else
        return false;

    return true;
}

但是,这甚至无法编译.然后,我尝试将非通用的方法包装在通用的方法中,例如

But this doesn't even compile. I then tried to wrap my non-generic metods in generic ones like

public string GetValue<string>(string field)
{
    return GetStringValue(field);
}

显然也不能编译.

可以做到这一点还是我必须为每种类型显式实现CopyValue?

Can this be done or do i have to explicitly implement CopyValue for each type?

推荐答案

您可以将其用于投射,但这很丑陋:

You can get it to work with casting, but it's ugly:

if (typeof(T) == typeof(string))
{
    copyAction((T)(object) GetStringValue(field));
}

(等)

老实说,这种事情总是以丑陋结束.一种选择是像这样创建Dictionary<Type, Delegate>:

This sort of thing always ends up being fairly ugly, to be honest. One option would be to create a Dictionary<Type, Delegate> like this:

Dictionary<Type, Delegate> fieldExtractors = new Dictionary<Type, Delegate>
{
    { typeof(string), (Func<string, string>) field => GetStringValue(field) },
    { typeof(int), (Func<string, int>) field => GetIntValue(field) },
};

然后您可以使用:

public bool CopyValue<T>(string field, Action<T> copyAction)
{
    Delegate fieldExtractor;
    if (fieldExtractors.TryGetValue(typeof(T), out fieldExtractor))
    {
        var extractor = (Func<string, T>) fieldExtractor;
        copyAction(extractor(field));
        return true;
    }
    return false;
}

这篇关于根据类型参数在通用方法中调用不同的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆