c# - 您能否将扩展方法的范围限制为具有特定属性的类?

标签 c# attributes extension-methods postsharp

我们有一个自定义的 FileExtensionAttribute,我们用它来装饰基于文件持久性的模型类。定义如下:

[AttributeUsage(AttributeTargets.Class, AllowMultiple=true, Inherited=true)]
public class FileExtensionAttribute : Attribute
{
    public FileExtensionAttribute(string fileExtension)
    {
        FileExtension = fileExtension;
    }

    public readonly string FileExtension;
}

我们还创建了以下扩展方法,以便更方便地检索这些扩展:

public static class FileExtensionAttributeHelper
{
    public static IEnumerable<string> GetFileExtensions(this Type type)
    {
        return type.CustomAttributes
            .OfType<FileExtensionAttribute>()
            .Select(fileExtensionAttribute => fileExtensionAttribute.FileExtension);
    }

    public static string GetPrimaryFileExtension(this Type type)
    {
        return GetFileExtensions(type).FirstOrDefault();
    }
}

在上面,对于没有指定属性的类型,这两个方法分别返回一个空枚举或null。但是,我们希望更主动地首先阻止此类调用。

虽然如果在指定类型上没有找到这样的属性我们可以很容易地抛出异常,但我想知道是否有一种方法可以限制扩展方法的调用只支持首先设置了该属性的类型所以这是一个编译时错误,而不是必须在运行时处理的错误。

那么是否可以将扩展方法限制为仅支持具有给定属性的类型?如果是,怎么办?

注意:我认为这在纯 C# 中可能是不可能的,但也许可以使用类似 PostSharp 的东西。

最佳答案

目前不支持。扩展方法是有限的,但可以非常强大。我很好奇为什么返回一个空列表是一个问题,我认为这将是理想的。如果它为空或 null,则什么也不做,没什么大不了的——生活还要继续。

为了更直接地回答你的问题,不。对于编译时错误,您不能通过属性限制扩展方法。

关于c# - 您能否将扩展方法的范围限制为具有特定属性的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33703791/

相关文章:

c# - EDMX 生成 Nullable bool 而不是 bool

c# - 从导航堆栈中删除时从 UIViewController 中删除数据

jquery - 使用 .each 分配多个元素属性?

javascript - 在没有 jQuery 的情况下将属性从 data-src 更改为 src

DOM 元素数组上的 jQuery 选择行为

c# - 获得一个无参数的方法来像 Func<Return>

c# - ASP.NET MVC Controller 扩展方法使日志对所有 Controller 可用

c# - 如何使用扩展方法使集合成为 "n"元素长?

c# - 根据用户声明授权访问 Controller

c# - 系统.MissingMethodException : Error while deserialization of json array