我有这个功能:
public int func1 (int x, int y)
{
return Math.Max(x, y);
}
我想要做的是,该函数将返回我或min或max取决于我将作为参数发送的内容,例如:
public static int func1 (int x, int y ,string minMax)
{
return Math.minMax(x, y);
}
static void Main(string[] args)
{
string x = "Max";
Console.WriteLine(func1(1, 2, x));
}
我希望我可以使用Max的属性,在字符串上使用我该怎么做?
谢谢!
答案 0 :(得分:2)
这应该有效:
public static int func1(int x, int y, string minMax)
{
return (int)typeof(Math).GetMethod(minMax, new[] { typeof(int), typeof(int) }).Invoke(null, new object[] { x, y });
}
private static void Main(string[] args)
{
Console.WriteLine("Max Wanted :" + func1(1, 2, "Max"));
Console.WriteLine("Min Wanted :" + func1(1, 2, "Min"));
}
答案 1 :(得分:0)
public static int func1 (int x, int y ,string minMax)
{
if(minMax == "Min")
{
return Math.Min(x,y);
}
else if (minMax == "Max")
{
return Math.Max(x,y);
}
else
{
// Not sure what you want to do here in your program.
}
}
答案 2 :(得分:0)
我怀疑
if("Max".Equals(minMax)) {
// code for max
} else {
// code for min
}
会起作用。
我建议阅读控制结构。这是非常基本的东西,如果你还没有,你真的应该知道如何使用它们。
这应该有助于C#中的if / else结构:https://msdn.microsoft.com/en-us/library/5011f09h.aspx
另外,我把“Max”放在首位的原因是为了避免Nullpointer异常。
答案 3 :(得分:0)
要添加其他答案,我个人会有两种不同的方法(即只使用Math.Max
或Math.Min
),但如果您需要一种方法,我会改用bool
一个string
。其中一个主要原因是您避免了区分大小写的问题,并且由于只有两个选项,因此布尔值适合于此。或者,您可以使用Enum。
public static int FindMinOrMax(int x, int y, bool findMax)
{
return findMax ? Math.Max(x, y) : Math.Min(x, y);
}
编辑从其他评论中,我了解到您要实现的目标。虽然我不推荐它,但你可以这样做
public static int FindMinMax(int x, int y, string method)
{
MethodInfo mi = typeof(Math).GetMethod(method, new[] { typeof(int), typeof(int) });
return (int)mi.Invoke(null, new object[] { x, y} );
}
方法区分大小写,因此Max
会起作用,但max
不会,因为方法称为Max
。你不能只是一直把第一个字母大写(除非它只是Min
/ Max
),因为DivRem
有骆驼套管。
+1 to Toto as he/she answered first, I just edited and noticed but will keep this post for completion
答案 4 :(得分:0)
你想要做的是使用Reflection通过名称唤起一个函数。
在这种情况下,我建议使用类似用户keyboardP建议的解决方案,因为它可以防止调用者传递无效值。
但是,这正是您所要求的:
public static int MaxOrMin(int x, int y, string methodName)
{
Type mathType = typeof(Math);
MethodInfo method = mathType.GetMethod(methodName);
if (methodName.ToLower() != "max" || methodName.ToLower() != "min")
throw new InvalidOperationException("Please specify Max or Min as the method name.");
object result = method.Invoke(null, new object[] { x, y });
return (int)result;
}
参考:This answer