我正在创建一个基类。我希望如果它被某个派生类继承,它必须应用一个属性,否则会抛出编译错误。可能吗?
public class MyAttribte : Attribute
{
public string TestString {get; set; }
}
public class Base
{
}
/*Attribute must be applied else throw compile time error.*/
[MyAttribte]
public class Derived : Base { }
请您参考如下方法:
你不能强制,但如果未指定 Attribute,你可以在运行时检查并抛出异常。
var d1 = new Derived1(); // OK
var d2 = new Derived2(); // throw error at run-time
public class Base
{
public Base()
{
CheckCustomAttribute();
}
private void CheckCustomAttribute()
{
if (!(this.GetType() == typeof(Base))) // Ingore Base for attribute
{
// var attr = System.Attribute.GetCustomAttributes(this.GetType()).SingleOrDefault(t=>t.GetType() == typeof(CustomAttribute));
var attr = System.Attribute.GetCustomAttributes(this.GetType()).SingleOrDefault(t => typeof(CustomAttribute).IsAssignableFrom(t.GetType())); // to include derived type of Custom attribute also
if (attr == null)
{
throw new Exception(String.Format("Derived class {0} doesnot apply {1} attribute", this.GetType().Name, typeof(CustomAttribute).Name));
}
}
}
}
[CustomAttribute]
class Derived1 : Base
{
}
class Derived2 : Base
{
}
class CustomAttribute : System.Attribute
{
}
