自定义属性,可能会生成编译时错误 [英] Custom Attribute that can generate compile time error

查看:303
本文介绍了自定义属性,可能会生成编译时错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个界面:

  public interface IBaseInterface 
{
void Base();
}

我使用它像:

  public class BaseClass:IBaseInterface 
{
public void Base()
{

} $ b但是,我想实现一个属性:









$ b b

  public class BaseClass:IBaseInterface //生成编译时错误
{
public void Base()
{

}
}

我只想使用界面如下:

  public interface IAdditionalBaseInterface:IBaseInterface 
{

}

public class AdditionalBaseClass:IAdditionalBaseInterface //没有编译时错误
{
public void Base()
{

}
}

可以有一个自定义属性这是做什么?我知道 ObsoleteAttribute 但是想知道这甚至如何工作,或更多,如何实现我自己的具有相同的编译时错误功能。

解决方案

ObsoleteAttribute 在编译器中是硬编码的,具有相同的行为。还要注意它生成一个编译时警告,或者如果属性的 IsError 属性设置为 true



你可能做的是一个自定义代码分析(FxCop)规则,它将在构建时执行反射/内省工作。但它不会像使用属性一样容易。



请参阅 http://www.binarycoder.net/fxcop/html/index.html FxCop SDK



不肯定会是一个有用的用例,无论如何,这种方式打败了OOP的概念。


I have an interface:

public interface IBaseInterface
{
    void Base();
}

And I use use it like:

public class BaseClass : IBaseInterface
{
    public void Base()
    {

    }
}

However, I want to implement an attribute such that:

public class BaseClass : IBaseInterface // Generates Compile-Time Error
{
    public void Base()
    {

    }
}

I only want to be able to use the interface like this:

public interface IAdditionalBaseInterface : IBaseInterface
{

}

public class AdditionalBaseClass : IAdditionalBaseInterface // No Compile-Time Error
{
    public void Base()
    {

    }
}

Is it possible to have a custom Attribute which does this? I am aware of the ObsoleteAttribute but was wondering how this even works, or more so, how I can implement my own which has the same compile-time error functionality.

解决方案

The ObsoleteAttribute is hardcoded in the compiler, you won't be able to have the same behavior. Also do note it generates a compile-time warning, or an error if the IsError property of the attribute is set to true.

What you probably could do is a custom Code Analysis (FxCop) rule, that will do the reflection/introspection job on build. But it won't be as easy to use as an attribute.

See http://www.binarycoder.net/fxcop/html/index.html for the FxCop SDK

Not sure what would be a useful use case anyway, this kind of defeats the OOP concepts.

这篇关于自定义属性,可能会生成编译时错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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