简体   繁体   English

通过反射获取Explicit Cast运算符

[英]Get Explicit Cast operators via reflection

Can I get cast operators via reflection and invoke (or if there's a better name for that action) them? 我可以通过反射和调用(或者如果有一个更好的名称来表示)它们来获得演员吗? That's the main question, if yes, it solves my problem. 这是主要问题,如果可以,它可以解决我的问题。

But if someone knows another solution to the following: 但是,如果有人知道以下解决方案:

I have many object vars (unknown quantities until runtime), each one have a different type, but all of them are numbers (double, int, short). 我有很多对象变量(运行时之前未知数量),每个变量都有不同的类型,但是它们都是数字(双精度,整数,短整数)。

On the other hand, I've got the same number of double vars, and need to compare values each to each. 另一方面,我有相同数量的双变量,并且需要将每个变量的值进行比较。

object[] Value1; //this can be double, short or int, only known at runtime.
double[] Value2;

//I need simply to do:
(for int i = 0; i < Value1.Length, i++)
{
    (if Value1[i] == Value2[i]) //here's the problem
    //the comparison always return false, because of different types
    ....

I've tryed many things, including the "CompareTo" method invoked via reflection, but it demands that de object vars are of the same type of the instance containing the method invoked. 我尝试了很多事情,包括通过反射调用的“ CompareTo”方法,但是它要求de object vars与包含调用的方法的实例具有相同的类型。 (Cannot call from a double and pass an int parameter, nor call from int and pass a double parameter) (不能从double调用并传递int参数,也不能从int调用并传递double参数)

So, if I could just cast them: One way is from double to the unknown type (for that I'd have to use some reflection) The other way is a two step casting from object to the unknown type, and from that to double. 因此,如果我可以将它们强制转换:一种方法是从double转换为未知类型(为此,我必须使用一些反射)另一种方法是将对象从对象转换为未知类型,然后从该类型转换为double 。

Limitations: 限制:

  • dynamic is not an option (old framework) 动态不是一个选择(旧框架)

  • Value1 items come individually "as object" from an external unchangeable method. Value1项分别通过外部不变方法“作为对象”出现。

Change Value1 to a double[] . Value1更改为double[] If you have an object to put into it (instance of short , int , double , etc.), use Convert.ToDouble(value) , or if you have a known short or int , it will be implicitly converted to a double . 如果要放入object (例如shortintdouble等),请使用Convert.ToDouble(value) ;如果您知道一个shortint ,则它将隐式转换为double These can then be compared with the double s in Value2 . 然后可以将它们与Value2double进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM