如何允许方法接受字符串或int?

时间:2011-02-05 15:18:08

标签: c# .net c#-4.0 methods

使用C#4.0,是否有办法允许方法(不创建重载)接受字符串或int,然后允许我检测传入的类型?

4 个答案:

答案 0 :(得分:17)

由于您使用的是C#4.0,因此可以编写generic method。例如:

void MyMethod<T>(T param)
{
    if (typeof(T) == typeof(int))
    {
        // the object is an int
    }
    else if (typeof(T) == typeof(string))
    {
        // the object is a string
    }
}

但你应该认真考虑这是不是一个好主意。上面的例子有点代码味道。事实上,泛型的全部意义是泛型。如果你必须根据传入的对象的类型对你的代码进行特殊处理,那么这就是你应该使用重载的标志。这样,每个方法重载处理其独特的情况。我无法想象这样做有什么不利之处。

答案 1 :(得分:4)

当然可以!一个例子是

    public void MyMethod(object o)
    {
        if (o.GetType() == typeof(string))
        {
            //Do something if string
        }
        else if (o.GetType() == typeof(int))
        {
            // Do something else
        }
    }

答案 2 :(得分:1)

您可以使用标记接口将 string int 包装在一些包装器中,并将它们传递给方法。

像这样的东西

interface IMyWrapper<T> { T Value {get; }}
public class StringWrapper: IMyMarker<string> { ... }
public class IntWrapper: IMyMarker<int> { ... }

void MyMethod<T>(IMyWrapper<T> wrapper)
{
}

答案 3 :(得分:1)

如果您想远离反射或检查类型之类的东西,我认为方法重载将是一个简单的解决方案。

public void MethodName(string foo)
{
     int bar = 0;
     if(int.tryparse(foo))
        return MethodName(bar);//calls int overload
}