微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我有一个通用的方法
public static void DoSomething<T>()
{...}

.现在我想限制那个T.

public static void DoSomething<T>() where T: IInterface1
{...}

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

public static void DoSomething<T>() where T: IInterface1,IInterface2
{...}

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

There’s no implicit conversion from IInterface1 to IInterface2

There’s no implicit conversion from IInterface2 to 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;
    }

方法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);
    }

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

解决方法

这对我来说很好:
interface I1 { int NumberOne { get; set; } }
interface I2 { int NumberTwo { get; set; } }

static void DoSomething<T>(T item) where T:I1,I2
{
    Console.WriteLine(item.NumberOne);
    Console.WriteLine(item.NumberTwo);
}

所以语法看起来很好……也许是导致问题的其他因素.

原文地址:https://www.jb51.cc/csharp/243577.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐