c# - 如何在运行时为类的新实例设置属性值
问题描述
当我创建对象时,我试图在方法上设置一个属性,但不确定如何去做(或者如果可能的话)。
这是我迄今为止尝试过的:
public abstract class AbstractClass
{
public abstract string DynamicAttributeValue { get; }
public AbstractClass()
{
// Set the Attribute on THIS instance
TypeDescriptor.AddAttributes(typeof(AbstractClass).GetMethod("MyMethod"),
new Attribute[] {
new ConditionalAttribute(DynamicAttributeValue)
});
}
public void MyMethod()
{
}
}
class MyConcreteClass : AbstractClass
{
public override string DynamicAttributeValue => "MyRunTimeValue";
static void Main(string[] args)
{
MyConcreteClass myClass = new MyConcreteClass();
string callingMethodName = "MyMethod";
MethodInfo methodInfo = myClass.GetType().GetMethod(callingMethodName);
var attributes = methodInfo.GetCustomAttributes();
}
}
解决方案
推荐阅读
- r - sparklyr::spark_write_jdbc 不接受 Spark 数据帧?
- python - Python:.format(name, age) 在这个称为封装的套件中做了什么?
- python - 从 json dict 中删除的 Python 不起作用
- typescript - Jest 抛出 TypeError: (0 , _module.myFunction) is not a function,用 Jest 测试导出的函数(非默认)
- node.js - 我想在猫鼬中使用 upsert 插入文档
- encoding - Python 编码字符串问题:字符串“Île-de-France”正在以“√éle-de-France”的形式写入 CSV 文件
- excel - 如何对包含日期和时间的excel中的列进行排序?
- python - 将列表元素与 Pandas 中的子列表元素进行比较
- javascript - 将输入集中在模态中时的性能问题?
- python - 如何在类中使用 FastAPI 创建路由