小编And*_*ott的帖子

使用通用逻辑扩展C#接口而不使用扩展方法

有没有办法在不使用扩展方法的情况下扩展接口?

如果我用一些get/set字符串定义一些接口,例如:

public interface IMyItem
{
    string Title { get; set; }
    string Description { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我想为这些接口添加一些简单的验证,但不必重新定义逻辑或强制某种形式的继承.

目前我正在使用扩展方法,如下所示:

public static class MyItemExtensions
{
    public static bool ERROR(this IMyItem item)
    {
        return item.TITLE_ERROR() || item.DESCRIPTION_ERROR();
    }

    public static bool TITLE_ERROR(this IMyItem item)
    {
        return string.IsNullOrEmpty(item.Title);
    }

    public static bool DESCRIPTION_ERROR(this IMyItem item)
    {
        return string.IsNullOrEmpty(item.Description);
    }
}
Run Code Online (Sandbox Code Playgroud)

这样做有用,我可以:

public class Item : IMyItem
{
   public string Title { get; set; }
   public string Description { get; set; } …
Run Code Online (Sandbox Code Playgroud)

.net c# extension-methods interface c#-4.0

2
推荐指数
1
解决办法
673
查看次数

标签 统计

.net ×1

c# ×1

c#-4.0 ×1

extension-methods ×1

interface ×1