gpt4 book ai didi

c# - 使用类型为 DataType 的泛型方法

转载 作者:行者123 更新时间:2023-11-30 12:10:06 26 4
gpt4 key购买 nike

这是 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[] 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;
}

像这样使用:

Test test = new Test();
long result = Transform(test.ReturnType, test.MyMethod(1,2,3,4));

但如您所知,我不能像这样使用泛型方法,我不想像这样显式声明返回类型:

long result = Transform<long>(test.MyMethod(1,2,3,4));

有什么建议吗?

最佳答案

如果不进行反射(reflection),就不可能准确地提出您要问的问题。

您可以将 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

关于c# - 使用类型为 DataType 的泛型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19466110/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com