我的类型变量很少
Int16[], Double[]
我将它们推送到这样的函数
Int16[] variable = ...;
Func(variable);
或
Double[] variable = ...;
Func(variable);
///////////////////////////////
private void Func(Object input)
{
var data = (input.GetType())input; ?????
//some actions with data
}
在这种情况下
var data = input.ToString();
数据变成内容为“System.Int16[]”或“System.Double[]”的字符串
如何将输入对象转换为 func 中的 Int16[] 或 Double[] 类型,即数据应该是 Int16[] 或 Double[] 数组或我可以在 func 中推送的任何类型例如此操作:
for(int i = 0; i < data.length; ++i)
{
data[i] = data[i] * 5;
}
最佳答案
这里有几个选项,首先您可以使用通用函数:
private void MyFunction<T>(T[] values)
{
for (int i = 0; i < values.Length; i++)
{
//Here is where the issue is, you can't constrain T to a value type that
//defines mathematical operators, so the best you can do is dynamic:
values[i] = (dynamic)values[i] * 5;
}
}
或者你可以这样做:
private void MyFunction(object values)
{
//Assume that object is an array, and go from there
for (int i = 0; i < ((dynamic)values).Length; i++)
{
((dynamic)values)[i] = ((dynamic)values)[i] * 5;
}
}
我认为这更肮脏。无论哪种方式,您都应该在这些函数的顶部进行某种类型检查,以验证传入的参数是否为数字数组类型,然后再假设它是数字数组类型并运行代码。
您发布的行:
var data = (input.GetType())input;
显然不起作用,因为 GetType()
返回一个 System.Type
,它在编译时不会将自身替换为类型的名称,所以它不是一个有效的类型转换。
关于c# - 如何将对象转换为c#类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33571378/