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

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

问题描述

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






更新:也许更好要使用 Assert.Fail()吗?



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

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

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


public class Bar< T>
其中T:class,new()
{
static Bar()
{
//如果Foo类型的多个成员具有MyCustomAttribute
//应用于它编译错误或Assert.Fail()?
}
}


解决方案

可以使用诊断指令:

  #error糟糕。这是一个错误。 

或只是警告:

  #warning这只是一个警告。 

你通常想把它们放在条件块中, p>

编辑:好的,现在你已经更新了你的问题,你根本不能在编译时这样做。您建议使用 Assert.Fail 将问题转嫁到执行时间。



我建议您编写单元测试检测这种情况(遍历程序集中的所有类型,并检查该属性在每个类型中最多只应用一次)。



编辑:2016年...而由OP建议的代码分析实际上并不是一个编译器错误,现在Visual Studio使用Roslyn,挂钩到编译器并真正从编译器获取错误是可行的,使用Roslyn代码分析仪。不过,我仍会 仍然 个人优选单元测试,因为然后代码可以由任何人建立和测试,无论他们是否安装了Roslyn分析器。仍然没有办法用纯粹的香草C#编译器来验证这一点。


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()?
    }
}

解决方案

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.

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

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