Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/apache/8.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#_Generics_Reflection - Fatal编程技术网

C# 在运行时执行隐式强制转换

C# 在运行时执行隐式强制转换,c#,generics,reflection,C#,Generics,Reflection,所以我有一个带有隐式转换的泛型类(主要是容器类),如下所示: public class Container<T> { public T Value { get; set; } public static implicit operator T(Container<T> t) { return t.Value; } public static implicit

所以我有一个带有隐式转换的泛型类(主要是容器类),如下所示:

public class Container<T>  
{  
        public T Value { get; set; }

        public static implicit operator T(Container<T> t)
        {
            return t.Value;
        }

        public static implicit operator Container<T>(T t)
        {
            return new Container<T>() { Value = t };
        }
} 
公共类容器
{  
公共T值{get;set;}
公共静态隐式运算符T(容器T)
{
返回t.值;
}
公共静态隐式运算符容器(T)
{
返回新容器(){Value=t};
}
} 
因此,在运行时,我想使用反射将
容器的一个实例强制转换为int,但似乎找不到方法,我已经尝试了几个地方提到的“cast”方法调用,但我得到的
指定强制转换无效。
异常


任何帮助都将不胜感激。

通过使用dlr,可以在nuget中通过开源访问,您可以动态访问

虽然这个例子相当繁琐,可以通过

int intInstance = (dynamic) containerInstnace;

还有。但是,如果您在编译时不知道
int
,则可以采用即兴方式。

编写隐式运算符可以隐式进行转换。换句话说,这是完全合法的:

int i = new Container<int>() { Value = 2 };
if (i == 2) 
{
    // This will be executed
}
inti=newcontainer(){Value=2};
如果(i==2)
{
//这将被执行
}

如果您只有一个
容器
,那么这将不起作用,但在这种情况下,您的代码可能无论如何都应该重构,因为您实际上忽略了您拥有的泛型参数。

除非所讨论的类型是无法修改的程序集的内部类型,否则几乎没有理由这样做

但是如果是这样的话,我个人更喜欢更干净的
动态
解决方案(正如jbtule所提到的)而不是反射

但是,由于您要求使用反射解决方案(也许您使用的是.NET 3.5或更早版本?),您可以:

object obj = new Container<int>();

var type = obj.GetType();
var conversionMethod = type.GetMethod("op_Implicit", new[] { type });
int value = (int)conversionMethod.Invoke(null, new[] { obj });
objectobj=newcontainer();
var type=obj.GetType();
var conversionMethod=type.GetMethod(“op_Implicit”,new[]{type});
int value=(int)conversionMethod.Invoke(null,new[]{obj});

那么编译时您知道什么,执行时您知道什么?你能给我们调用代码吗?你是想将容器“强制转换”为int还是Container.Value?为什么不直接调用
Container.Value
?我不一定知道泛型变量的实例有一个“Value”属性,这只是一个简化的示例,本质上我想(尝试)将容器变量强制转换为其包含的类型,例如,将
Tuple
转换为
int
,假设
Tuple
实际上对其包含的类型进行了隐式强制转换,或者像我的容器一样,将
容器
转换为
客户
object obj = new Container<int>();

var type = obj.GetType();
var conversionMethod = type.GetMethod("op_Implicit", new[] { type });
int value = (int)conversionMethod.Invoke(null, new[] { obj });