C#调用超载功能时自动铸造



让我们想象我有以下超载函数:

void DoSomething(int x) { ... }
void DoSomething(float x) { ... }
void DoSomething(decimal x) { ... }

在以下方法中,我需要调用正确的过载。这就是一个简单的实现的样子:

void HaveToDoSomething(object data)
{
    if (data is int) DoSomething((int)data);
    else if (data is float) DoSomething((float)data);
    else if (data is decimal) DoSomething((decimal)data);
}

当有20种类型的检查时,这很乏味。是否有更好的方法可以自动进行所有这些铸造?

我忘了提到的东西: DoSomething无法与仿制药一起使用,因为每种类型都需要以不同的方式处理,我只知道运行时的类型。

一种可能的方法是使用 dynamic

void HaveToDoSomething(dynamic data)
{
    DoSomething(data);
}

您可以使用Reflection,但可以产生性能影响:

public class Example
{
    void DoSomething(int i)
    {
    }
    void DoSomething(float i)
    {
    }
}
public static class ExampleExtensions
{
    public static void DoSomethingGeneric(this Example example, object objectParam)
    {
        var t = objectParam.GetType();
        var methods = typeof(example).GetMethods().Where(_ => _.Name == "DoSomething");
        var methodInfo = methods.Single(_ => _.GetParameters().First().ParameterType == t);
        methodInfo.Invoke(example, new[] { objectParam });
    }
}

最新更新