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

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

问题描述

简单的问题,你怎么强制C#编译器抛出一个编译错误。


更新:也许这是最好使用 Assert.Fail()而不是

我应该只适用于一类的一个成员的自定义属性。在我的其他类的静态方法,它看起来对于一个成员,我希望它失败(不抛出异常),如果多个成员有属性适用于它。

 公共类Foo
{
    [MyCustomAttribute]
    公共字符串FooString {获得;组; }

    [MyCustomAttribute]
    公共字符串OtherFooString {获得;组; }
}


公共类酒吧< T>
    其中T:类,新的()
{
    静吧()
    {
         //如果类型的多个成员的Foo具有MyCustomAttribute
         //应用到它编译错误或Assert.Fail()?
    }
}
 

解决方案

您可以使用诊断指令:

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

或只是一个警告:

 指令#warning这只是一个警告。
 

你通常要在条件块把这些,我期望......

编辑:好了,现在你已经更新了你的问题,你根本无法在编译时做到这一点。您使用的建议 Assert.Fail 平底船的问题的执行时间。

我会建议你写单元测试来检测这个(迭代在装配了所有的类型,并检查该属性只被每类应用最多一次)。

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

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

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