如果多个成员具有相同的属性,如何抛出编译器错误 [英] How to throw a compiler error if more than one member has the same Attribute

查看:15
本文介绍了如果多个成员具有相同的属性,如何抛出编译器错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单的问题,如何强制C#编译器抛出编译错误.

Simple question, how do you force the C# compiler to throw a compilation error.

更新:也许改用 Assert.Fail() 更好?

Update: Perhaps it's better to use an Assert.Fail() instead?

我有一个自定义属性,它应该只应用于一个类的一个成员.在我的另一个类的静态方法中,它会查找该成员,如果有多个成员应用了该属性,我希望它失败(而不是抛出异常).

I have a custom-attribute that should only be applied to ONE member of a class. Inside of my other class' static method it looks for that one member and I want it to fail (not throw an exception) if more than one member had the attribute applied to it.

public class Foo
{
    [MyCustomAttribute]
    public String FooString { get; set; }

    [MyCustomAttribute]
    public String OtherFooString { get; set; }
}


public class Bar<T>
    where T : class, new()
{
    static Bar()
    {
         //If more than one member of type Foo has MyCustomAttribute
         //applied to it compile error or Assert.Fail()?
    }
}

推荐答案

您可以使用诊断指令:

#error Oops. This is an error.

或者只是一个警告:

#warning This is just a warning.

您通常希望将这些放在条件块中,我希望...

You'd normally want to put these in conditional blocks, I'd expect...

好的,现在您已经更新了您的问题,您根本无法在编译时执行此操作.您使用 Assert.Fail 的建议将问题推到了执行时间上.

Okay, now you've updated your question, you simply can't do this at compile-time. Your suggestion of using Assert.Fail punts the problem to execution time.

我建议您编写单元测试来检测这一点(迭代程序集中的所有类型,并检查该属性是否最多只应用于每个类型一次).

I would suggest you write unit tests to detect this (iterate over all the types in the assembly, and check that the attribute has only been applied at most once per type).

在 2016 年...虽然 OP 建议的代码分析实际上不是编译器错误,但既然 Visual Studio 使用 Roslyn,那么挂钩到编译器并真正得到来自编译器的错误,使用 Roslyn 代码分析器.但是,我个人仍然更喜欢为此进行单元测试,因为这样任何人都可以构建和测试代码,无论他们是否安装了 Roslyn 分析器.仍然无法使用纯粹的"C# 编译器来验证这一点.

In 2016... while Code Analysis as suggested by the OP isn't actually a compiler error, now that Visual Studio uses Roslyn, it's feasible to hook into the compiler and genuinely get an error from the compiler, using a Roslyn code analyzer. However, I would still personally prefer unit tests for this, as then the code could be built and tested by anyone, regardless of whether they had the Roslyn analyzer installed. There's still no way of validating this with a "purely vanilla" C# compiler.

这篇关于如果多个成员具有相同的属性,如何抛出编译器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆