C# 对数据类型使用泛型方法
这是ITest接口:C# 对数据类型使用泛型方法,c#,generics,type-conversion,C#,Generics,Type Conversion,这是ITest接口: public interface ITest { Type ReturnType { get; } Object MyMethod(params object[] args); } 和测试等级: public class Test: ITest { public Type ReturnType { get { return typeof(long); } } public Object MyMethod(params object[]
public interface ITest
{
Type ReturnType { get; }
Object MyMethod(params object[] args);
}
和测试等级:
public class Test: ITest
{
public Type ReturnType { get { return typeof(long); } }
public Object MyMethod(params object[] args)
{
long sum = 0;
foreach(object arg in args)
{
sum += (long)arg;
}
return sum;
}
}
因此,我需要一种方法,可以自动转换ITest
方法与ReturnType
类型的结果
我是这样想的:
public T Transform<T>(Type T, object result)
{
return (T)result;
}
但正如您所知,我不能像这样使用泛型方法,我不想像这样显式地声明返回类型:
long result = Transform<long>(test.MyMethod(1,2,3,4));
long result=Transform(test.MyMethod(1,2,3,4));
有什么建议吗?如果没有思考,就不可能准确地回答你的问题 您可以将ITest标记为
Generic
,从此一切都变得简单了
public interface ITest<T>
{
Type ReturnType { get; }//redundatnt
T MyMethod(params object[] args);
}
public class Test : ITest<long>
{
public Type ReturnType { get { return typeof(long); } }//redundatnt
public long MyMethod(params object[] args)
{
long sum = 0;
foreach (object arg in args)
{
long arg1 = Convert.ToInt64(arg);
sum += arg1;
}
return sum;
}
}
Test test = new Test();
long result = test.MyMethod(1,2,3,4);//No transform nothing, everything is clear
公共接口测试
{
类型ReturnType{get;}//redundantnt
T MyMethod(参数对象[]参数);
}
公共类考试:ITest
{
公共类型ReturnType{get{return typeof(long);}}//redundantnt
公共长MyMethod(参数对象[]args)
{
长和=0;
foreach(args中的对象arg)
{
长arg1=Convert.ToInt64(arg);
sum+=arg1;
}
回报金额;
}
}
测试=新测试();
长期结果=试验方法(1,2,3,4)//没有,什么都没有,一切都很清楚
反射是必需的,但重要的是,这种方法非常可疑,而且不是100%可能的,因为您无法将对象
强制转换为长
。请尝试运行以下命令:
static void Main()
{
int i = 1;
object o = i;
long l = (long)o;
}
正如Sriram所演示的,可以实现特定于类型的方法,但我认为这会破坏问题/设计的目的。简单地使用带有不同参数类型(如int[]和long[]等)的重载方法也会更容易,这有助于确保强制转换不会引发异常。正如@nawfal所述,您可以将ITest用作泛型:
public interface ITest<T>
{
T MyMethod(params object[] args);
}
公共接口测试
{
T MyMethod(参数对象[]参数);
}
反射是一种选择吗?那么它是有可能的这根本不可能(据我所知)为什么不想将类型参数传递给泛型方法?为什么ITest
no-generic?@nawfal你是对的,这是一个很好的选择。我会说这种方法违背了问题的目的。你也不能保证Convert.ToInt64
对作为参数传入的对象有效。@Moho你应该知道方法在做什么以及需要传入什么这是10分钟前回答的问题,更多细节。这肯定不能回答问题question@SriramSakthivel虽然你是对的,但我看到一些成员以这样的方式回答OP方法中的潜在陷阱,甚至是来自知名成员。我发现,很多时候,关于SO的问题的真正答案不是如何按照请愿人的意愿让某些东西发挥作用,但要帮助他们理解为什么他们的方法很难(即它是不正确的)。
public interface ITest<T>
{
T MyMethod(params object[] args);
}