How can I allow a method to accept either a string or int?
Using C# 4.0, is there开发者_StackOverflow中文版 a way to allow a method (without creating an overload) to accept a string or an int and then allow me to detect what type was passed in?
Since you're using C# 4.0, you can write a generic method. For example:
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
}
}
But you should very seriously consider whether or not this is a good idea. The above example is a bit of a code smell. In fact, the whole point of generics is to be generic. If you have to special-case your code depending on the type of the object passed in, that's a sign you should be using overloading instead. That way, each method overload handles its unique case. I can't imagine any disadvantage to doing so.
Sure you can! An example of this is
public void MyMethod(object o)
{
if (o.GetType() == typeof(string))
{
//Do something if string
}
else if (o.GetType() == typeof(int))
{
// Do something else
}
}
You can wrap string and int in some wrapper with marker interface and pass them to a method.
Something like this
interface IMyWrapper<T> { T Value {get; }}
public class StringWrapper: IMyWrapper<string> { ... }
public class IntWrapper: IMyWrapper<int> { ... }
void MyMethod<T>(IMyWrapper<T> wrapper)
{
}
I would think a method overload would be a straightforward solution, if you want to stay away from stuff like reflection or checking types.
public void MethodName(string foo)
{
int bar = 0;
if(int.tryparse(foo))
return MethodName(bar);//calls int overload
}
精彩评论