c# - 界面以 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
。
解决方案
@LasseV.Karlsen 在评论中回答了它。我错过where T : class
了方法。
public static T MyExtensionMethod<T>(this IMyInterface<T> item, Guid id)
where T : class
{
// code
}
推荐阅读
- c# - 如何使用 .Net 核心在 Http Post 控制器中返回 IEnumerable json 数组
- r - 已解决:如何正确利用反应式表达式来让这个图在 RShiny 中工作?
- javascript - 从另一个网站内启动浏览器会话
- sql - 如何从 PostgreSQL 中的文本中删除分隔部分?
- c++ - 从 'wchar_t' 转换为 'const _Elem',可能会丢失数据
- php - 从包外部访问包配置值
- macos - 在 github 上使用 Sectigo 证书进行代码签名
- c++ - 在图遍历中找到最小路径的有效方法
- tailwind-css - 如何做光标:group-hover Tailwind Css中的指针?
- laravel - 通过 Laravel 8.x 中的控制器动态更改应用名称