如果多个成员具有相同的属性,如何引发编译器错误

How to throw a compiler error if more than one member has the same Attribute(如果多个成员具有相同的属性,如何引发编译器错误)

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

问题描述

简单问题,如何强制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.

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

本文标题为:如果多个成员具有相同的属性,如何引发编译器错误

基础教程推荐