Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

c# - How to throw a compiler error if more than one member has the same Attribute

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


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()?
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use a diagnostic directive:

#error Oops. This is an error.

or for just a warning:

#warning This is just a warning.

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

EDIT: 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).

EDIT: 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...