gpt4 book ai didi

c# - 关于int和double重载的问题

转载 作者:行者123 更新时间:2023-12-03 22:02:19 24 4
gpt4 key购买 nike

我有 2 个方法,intMethod 和 doubleMethod,它们完全相同,除了 intMethod 接受一个 int 数组参数而 doubleMethod 接受一个 double 数组参数。

我知道我可以使用重载来使用相同的方法名称,但是,我仍然得到 2 个几乎相同的方法,只是它们的参数不同。无论如何我可以将 intMethod 和 doubleMethod 组合成一种方法吗?

如果是这样,你能提供一些示例代码吗?我可以通过一些示例代码更好地理解。谢谢

编辑:人们要求我发布我的方法,然后就可以了:

我有一个相同的方法,readDataDouble,数据数组是 double[][]

基本上,此方法读取 CSV 文件并将数据转换为 int 格式。第一行是时间,第一列是日期。

    public static void readDataInt(string value, ref int[][] data, ref DateTime[] timeframe, ref DateTime[] date)
{
string inputFile = "D:\\temp.csv";
string[][] temp = null;

if (File.Exists(inputFile))
{
string[] proRataVolumeFile = File.ReadAllLines(inputFile);
temp = new string[proRataVolumeFile.Length][];

for (int i = 0; i < proRataVolumeFile.Length; i++)
{
temp[i] = proRataVolumeFile[i].Split(',');
}
}

//convert the string to int

date = new DateTime[temp.Length - 1];
timeframe = new DateTime[temp[0].Length - 1];
data = new int[temp.Length - 1][];

for (int i = 1; i < temp.Length; i++)
{
data[i - 1] = new int[temp[i].Length - 1];

for (int j = 1; j < temp[i].Length; j++)
{
if (temp[i][j].Length > 0)
data[i - 1][j - 1] = Convert.ToInt32(temp[i][j]);
}
}

for (int i = 1; i < temp.Length; i++)
{
date[i - 1] = Convert.ToDateTime(temp[i][0]);
}

for (int j = 1; j < temp[0].Length; j++)
{
timeframe[j - 1] = DateTime.Parse(temp[0][j]);
}
}

最佳答案

这在很大程度上取决于方法本身的作用。

如果方法可以写成共享接口(interface),比如IComparable<T> ,您可以将其设为 generic method :

void SomeMethod<T>(T[] values) where T : IComparable<T>
{
// Do stuff here
}

然而,这将更加严格,因为您只能使用通用约束定义的方法或属性。它适用于需要比较值或检查相等性等的事情,但不适用于“通用数学”,因为没有可用的共享接口(interface)(例如理论上的 IArithmetic<T> 接口(interface))。

编辑:在您的情况下,您应该能够使用受限于 IConvertible 的通用方法实现:

public static void ReadData<T>(string value, ref T[][] data, ref DateTime[] timeframe, ref DateTime[] date) where T : IConvertible
{

另一种选择是声明您的方法以使用dynamic而不是特定类型:

dynamic SomeMethod(dynamic[] values)
{
dynamic result = values[0];
for (int i = 1; i < values.Length; ++i)
result = result + values[i]; // You can use normal operators now
return result;
}

这适用于任何类型,但检查有效地转移到运行时,因为它使用动态绑定(bind)。如果您传递一个不能正常工作的类型,您将得到运行时异常(而不是编译时检查)。

关于c# - 关于int和double重载的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12607735/

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