gpt4 book ai didi

c# - 如何强制开发人员将属性应用于类?

转载 作者:太空宇宙 更新时间:2023-11-03 21:51:33 24 4
gpt4 key购买 nike

我正在创建一个基类。我希望如果它被某个派生类继承,它必须应用一个属性,否则会抛出编译错误。可能吗?

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
{
}

关于c# - 如何强制开发人员将属性应用于类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14272570/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com