以下是一些代码:
class Program
{
static void Main(string[] args)
{
MyClass class1 = new MyClass();
MyOtherClass class2 = new MyOtherClass();
Helper.UseAttribute<MyClass>(class1);
//Raise a warning to tell the developer that they cannot use this class
//as there is no property with the specified attribute.
Helper.UseAttribute<MyOtherClass>(class2);
}
}
public class MyAttribute : System.Attribute { }
class MyClass
{
[MyAttribute]
public string SomethingAwesome { get; set; }
}
class MyOtherClass
{
public string SomethingElseWhichIsAlsoPrettyAwesome { get; set; }
}
static class Helper
{
public static void UseAttribute<T>(T sender)
{
//Do something with the property that has MyAttribute
//If there isn't a property with this attribute, then raise
//a warning.
}
}
在理想情况下,我想限制开发人员将类传递给没有特定属性的方法。
我知道我可以使用接口或某些描述的基类,但问题实际上是否可能像上面的例子那样。
答案 0 :(得分:4)
如果您乐意使用VS 2015预览或等到VS 2015结束,您可以使用Roslyn进行此操作。
你要编写一个DiagnosticAnalyzer
类,可能会注册一个语法节点分析器来专门查找Helper.UseAttribute<T>
的调用。当您找到这样的用途时,您会找到T
的符号,并检查是否有适用于MyAttribute
属性的任何属性,如果没有,则发出警告。此警告将在Visual Studio中显示,并应用于CI构建(假设您正确注册了分析器组件)。
开始使用Roslyn诊断API需要一段时间,但是一旦习惯了它,真的功能强大。
当然,另一种选择是在执行时抛出一个异常,并依赖于所有调用者周围的单元测试,以便在失败时能够捕获它:)你应该这样做以及通过Roslyn添加编译时支持。
答案 1 :(得分:2)
你现在能做的最好就是在运行时处理它(并抛出异常或其他东西)。在设计/编译时,我认为还没有可能。
public static void UseAttribute<T>(T sender)
{
var hasAttribute = typeof(T).GetProperties().Any(prop => Attribute.IsDefined(prop, typeof(MyAttribute)));
if (!hasAttribute)
throw new Exception("Does not contain attribute");
}