Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 通用数据类型转换的最佳方法_C#_.net - Fatal编程技术网

C# 通用数据类型转换的最佳方法

C# 通用数据类型转换的最佳方法,c#,.net,C#,.net,我必须处理多个数据类型转换。我不想单独进行转换。有什么方法可以使用泛型转换器类来解决这个问题吗 请帮忙 更新:如何使参数也通用 private static T GetValueForParameter<T>(int temp) { T tempValue; tempValue = default(T); tempValue = (T)Convert.ChangeType(temp, typeof(T), CultureInfo.InvariantCultu

我必须处理多个数据类型转换。我不想单独进行转换。有什么方法可以使用泛型转换器类来解决这个问题吗

请帮忙

更新:如何使参数也通用

private static T GetValueForParameter<T>(int temp)
{ 
    T tempValue;
    tempValue = default(T);
    tempValue = (T)Convert.ChangeType(temp, typeof(T), CultureInfo.InvariantCulture);
    return tempValue;
}
private static T GetValueForParameter(int-temp)
{ 
tempt值;
tempValue=默认值(T);
tempValue=(T)Convert.ChangeType(temp,typeof(T),CultureInfo.InvariantCulture);
返回值;
}

要更改通用参数,只需定义另一个模板M即可。像这样更新了你的代码使用。希望这能回答你的问题

private static T GetValueForParameter<T,M>(M temp)
{
    T tempValue;
    tempValue = default(T);
    tempValue = (T)Convert.ChangeType(temp, typeof(T), CultureInfo.InvariantCulture);
    return tempValue;
}
private static T GetValueForParameter(M temp)
{
tempt值;
tempValue=默认值(T);
tempValue=(T)Convert.ChangeType(temp,typeof(T),CultureInfo.InvariantCulture);
返回值;
}

要更改通用参数,只需定义另一个模板M即可。像这样更新了你的代码使用。希望这能回答你的问题

private static T GetValueForParameter<T,M>(M temp)
{
    T tempValue;
    tempValue = default(T);
    tempValue = (T)Convert.ChangeType(temp, typeof(T), CultureInfo.InvariantCulture);
    return tempValue;
}
private static T GetValueForParameter(M temp)
{
tempt值;
tempValue=默认值(T);
tempValue=(T)Convert.ChangeType(temp,typeof(T),CultureInfo.InvariantCulture);
返回值;
}

请展开、解释、展示你的意思并研究:非常不清楚你在这里想要实现什么。你能详细说明一下吗?提供一些你已经尝试过的/你期望的例子?请扩展、解释、展示你的意思并研究:非常不清楚你在这里想要实现什么。你能详细说明一下吗?提供一些你已经尝试过的/你期望得到的例子?你能不能也发布调用方法?为什么不只是让参数成为一个对象?浮动x=20.0f;int f=GetValueForParameter(x);是的,我们可以将参数设置为对象,但正如前面提到的,他们希望在解决方案中使用泛型,所以…ChangeType不会适用于所有类型。只有当我记得正确的时候,我才可以转换。你可以后调用方法吗?为什么不只是让参数成为一个对象?浮动x=20.0f;int f=GetValueForParameter(x);是的,我们可以将参数设置为对象,但正如前面提到的,他们希望在解决方案中使用泛型,所以…ChangeType不会适用于所有类型。只有在我记忆正确的情况下我才能转换