Pass instance of Class as parameter to Attribute constructor(将 Class 的实例作为参数传递给 Attribute 构造函数)
问题描述
我需要自定义属性中的类/模型实例(用于访问非静态成员).
I need an instance of class/model(for the purpose of accessing a non-static member) within my custom attribute.
public class LoginModel
{
[AutoComplete(currentInstance)] //pass instance of class or CompanyNames
public string DepartmentName { get; set; }
public string[] DepartmentNames { get {...} }
}
有没有办法在不使用 new() 或反射的情况下做到这一点.
Is there a way to do this without using new() or Reflection.
推荐答案
这完全不可能.属性在编译时被烘焙到程序集的元数据中,因此谈论将类的实例传递给属性没有任何意义,因为实例仅在运行时存在.
That's totally impossible. Attributes are baked into the metadata of the assembly at compile-time so talking about passing an instance of a class to an attribute doesn't make any sense because instances exist only at runtime.
另一方面,属性总是被反射消耗掉,所以我猜现在您正在检查类元数据上是否存在此自定义属性,您可以使用该实例.
On the other hand attributes are always consumed by reflection, so I guess that at the moment you are checking for the presence of this custom attribute on the class metadata you could use the the instance.
这篇关于将 Class 的实例作为参数传递给 Attribute 构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 Class 的实例作为参数传递给 Attribute 构造函数
基础教程推荐
- Moq It.Is<>不匹配 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- WPF 模态进度窗口 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
