将一个对象同时投射到两个接口,以调用泛型方法 [英] Casting an object to two interfaces at the same time, to call a generic method

查看:16
本文介绍了将一个对象同时投射到两个接口,以调用泛型方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想调用一个泛型方法来约束输入类型T来实现两个接口:

I want to call a generic method that constrains the input type T to implement two interfaces:

interface IA { }
interface IB { }
void foo<T>(T t) where T : IA, IB { }

如何修复

void bar(object obj)
{
    if (obj is IA && obj is IB)
    {
        foo((IA && IB)obj);
    }
}

?

反射可能允许调用,但我想留在语言中.

Reflection probably allows to do the call, but I would like to stay within the language.

推荐答案

C# 4.0 动态关键字是否让您(大部分)从监狱中解脱出来?毕竟 - 您已经在进行类型检查.

Does the C# 4.0 dynamic keyword get you out of jail (mostly) free? After all - you are already doing the type checking.

interface IC : IA, IB { }

void bar(object obj)
{
  if (obj is IA && obj is IB)
  {
    IC x = (dynamic)obj;
    foo(x);
  }
}

如果 foo 试图将参数强制转换为 T 会中断吗?我不知道.

Does that break if foo tries to cast the parameter to T? I don't know.

这篇关于将一个对象同时投射到两个接口,以调用泛型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆