我可以将泛型方法限制为多个接口吗?

Tob*_*ias 6 c# generics where

我有一个通用的方法

public static void DoSomething<T>()
{...}
Run Code Online (Sandbox Code Playgroud)

.现在我想限制那个T.

public static void DoSomething<T>() where T: IInterface1
{...}
Run Code Online (Sandbox Code Playgroud)

但我真正想要的是允许多个接口,例如

public static void DoSomething<T>() where T: IInterface1, IInterface2
{...}
Run Code Online (Sandbox Code Playgroud)

但这不起作用.编译器说类似的东西

没有从IInterface1到IInterface2的隐式转换

没有从IInterface2到IInterface1的隐式转换

我想过让这些类实现一个我可以参考的公共接口,但是我没有访问这些类.

我有什么可能允许多个接口?

谢谢,托比

编辑:这就是我想要做的.我正在开发一个Outlook-Add-In.我经常使用下面这段代码.

    public static object GetItemMAPIProperty<T>(AddinExpress.MAPI.ADXMAPIStoreAccessor adxmapiStoreAccessor, object outlookItem, uint property) where T: Outlook.MailItem, Outlook.JournalItem
    {
        AddinExpress.MAPI.MapiItem mapiItem;
        mapiItem = adxmapiStoreAccessor.GetMapiItem(((T)outlookItem));
        return mapiItem != null ? mapiItem.GetProperty(property) : null;
    }
Run Code Online (Sandbox Code Playgroud)

方法GetMapiItem只需要一个对象,只要它是Outlook的一个项目(Journal,Mail,Contact,...).这就是为什么我限制T.因为它不能,比如,Outlook.MAPIFolder.

不,我已经改变了方法

    public static object GetItemMAPIProperty<T>(AddinExpress.MAPI.ADXMAPIStoreAccessor adxmapiStoreAccessor, T outlookItem, uint property)
    {
        AddinExpress.MAPI.MapiItem mapiItem;
        mapiItem = adxmapiStoreAccessor.GetMapiItem(((T)outlookItem));
        return mapiItem.GetProperty(property);
    }
Run Code Online (Sandbox Code Playgroud)

但是开发人员(在本例中为I)可以为其提供任何类型,因为GetMapiItem方法接受一个对象.我希望这是有道理的.我不确定它是否适用于该示例,但我想将通用方法限制为多个类型(使用OR)可能是一个好主意.

Atm*_*ons 1

一种方法是创建一个扩展接口 1 和 2 的附加接口。然后放置此接口而不是其他 2 个接口。

这是用java实现的一种方法;如果我没记错的话,这应该在 C# 中也能工作

希望有帮助。

问候,托比以及:P