Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/25.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,我有两种类型存储在字符串中,我需要得到产生加法/除法/…的类型。。。其中: "test" + 2 // would give "string" 2 - 2.2f // would give "float" 等等…… 如果其中一个不是基元或字符串(如System.DateTime),我已经可以这样做了,但我找不到如何做(清除)。。。 我现在最好的办法是在运行时构建这两个方法,并调用“GetResultType”方法: Type GetTemplateType<T>(T? t)

我有两种类型存储在字符串中,我需要得到产生加法/除法/…的类型。。。其中:

"test" + 2 // would give "string"  
2 - 2.2f // would give "float"  
等等……
如果其中一个不是基元或字符串(如System.DateTime),我已经可以这样做了,但我找不到如何做(清除)。。。 我现在最好的办法是在运行时构建这两个方法,并调用“GetResultType”方法:

Type GetTemplateType<T>(T? t) where T: struct => typeof(T);
Type GetResultType() => GetTemplateType(true ? null : ((int?)null) + ((double?)null));
当然,所有
“string”
变量也可以是
“System.Type”
变量…

我本来可以硬编码所有的可能性,但我正在寻找一种现有的方法来使用反射(或其他什么)来获得结果类型

不,不可能使用反射(或其他简单的方法)来获取“x+y”类型,因为编译器的工作是找到在这种情况下实际将调用的方法(包括正确搜索所有隐式强制转换和重载运算符)

选项:

  • 您可以复制控制运算符选择的编译器规则(硬)
  • 编译源代码,在运行时调用带有所需参数的运算符,并检查结果的类型(
    default(type)
    是获取样本值的方法
  • 如果您对类型的选择有限,您可以简单地硬编码所有可能的类型并存储在字典中
  • 将问题反向,并将可用运算符集限制为您已经知道的结果-例如在调用运算符之前将所有数值类型转换为
    double
  • 查看是否可以使用
    dynamic
    来获取类型(
    ((dynamic)x)+y).GetType()
    ),您需要了解如何为
    string
    等引用类型获取非空样本值

一个选项可能是为每种相关类型存储一组“样本数据”,然后使用您要查找的组合执行实际操作

例如(仅显示
string
float
但可扩展到所有相关类型):

//设置示例数据(按类型键入,但可以是类型的全名或其他名称)
DictionaryexampleTypes=newdictionary();
添加(typeof(string),“a”);
示例types.Add(typeof(float),1.0f);
//获取两位样本数据
动态优先=示例类型[类型(字符串)];
动态秒=示例类型[类型(浮动)];
//应用你感兴趣的计算
动态摆锤=第一+第二;
//好的,float+string结果是string
Console.WriteLine(bob.GetType());

嘿,关于
string+int
int-float
谢谢,你能在代码中给出一个更好的例子吗?你可以在实际代码中展示你是如何给变量赋值的,它的类型是
“test”+2//"string
,显示实际代码,而不是string+int值。如果你是决定结果类型的人,你可以在字典中硬编码,使用类型作为
,返回类型作为
我不决定结果类型,我只需要真正的结果类型我将其标记为已接受,因为在lea它不需要硬编码所有15*15的可能性,只需要一个15个值的数组。谢谢!
string GetResultingTypeOfAddition( string type1, string type2 ) { ... }
...
var type = GetResultingTypeOfAddition(node1.Type, node2.Type); 
// Setup sample data (keyed by Type, but could be Type's FullName or whatever really)
Dictionary< Type, object> exampleTypes = new Dictionary<Type, object>();
exampleTypes.Add(typeof(string), "a");
exampleTypes.Add(typeof(float), 1.0f);

// Get two bits of sample data
dynamic first = exampleTypes[typeof(string)];
dynamic second = exampleTypes[typeof(float)];

// Apply calculation you are interested in
dynamic bob = first + second;

// OK, float + string results in string
Console.WriteLine(bob.GetType());