首页 > 解决方案 > 界面以 T 作为扩展方法的返回类型

问题描述

也许我在这个问题上停留在我的观点上。我只想消除对演员表(MyClass)的需要。

var c = (MyClass)new MyClass { }.MyExtensionMethod();

MyClass 实现 IMyInferface

IMyInterface.cs

public interface IMyInterface<T>
        where T : class
{
    // props
}

MyInterfaceExtensions.cs

public static class MyInterfaceExtensions
{
    public static T MyExtensionMethod<T>(this IMyInterface<T> item, Guid id)
    {
         item.CreatedTimestamp = DateTime.UtcNow;
         item.MySecondExtMethod(id);
         return (T)item;
    }
}

而且我仍然收到错误“类型 T 必须是引用类型才能将其用作参数” this IMyInterface<T> item

标签: c#.netgenerics.net-coreextension-methods

解决方案


@LasseV.Karlsen 在评论中回答了它。我错过where T : class了方法。

public static T MyExtensionMethod<T>(this IMyInterface<T> item, Guid id)
     where T : class
{
   // code
}

推荐阅读