Can I use Attributes with Anonymous classes?(我可以将属性与匿名类一起使用吗?)
问题描述
我有一个匿名类:
var someAnonymousClass = new
{
SomeInt = 25,
SomeString = "Hello anonymous Classes!",
SomeDate = DateTime.Now
};
是否有附加属性到这个类?反射,其他?我真的很希望有这样的东西:
Is there anyway to attach Attributes to this class? Reflection, other? I was really hoping for something like this:
var someAnonymousClass = new
{
[MyAttribute()]
SomeInt = 25,
SomeString = "Hello anonymous Classes!",
SomeDate = DateTime.Now
};
推荐答案
您实际上是在创建所谓的匿名类型,而不是动态类型.
You're actually creating what is called an anonymous type here, not a dynamic one.
不幸的是,没有办法实现您想要做的事情.匿名类型是一种非常简单的不可变类型,由名称/值对组成.
Unfortunately no there is no way to achieve what you are trying to do. Anonymous types are meant to be a very simple immutable type consisting of name / value pairs.
匿名类型的 C# 版本仅允许您自定义基础类型上的名称/值对集.没有其他的.VB.Net 允许更多的自定义,因为这些对可以是可变的或不可变的.但是,它们都不允许您使用属性来增加类型.
The C# version of anonymous type only allows you to customize the set of name / value pairs on the underlying type. Nothing else. VB.Net allows slightly more customization in that the pairs can be mutable or immutable. Neither allow you to augment the type with attributes though.
如果你想添加属性,你需要创建一个完整的类型.
If you want to add attributes you'll need to create a full type.
EDIT OP 询问是否可以通过反射添加属性.
EDIT OP asked if the attributes could be added via reflection.
不,这是不可能的.反射是一种检查元数据而不改变它的方法.因此它不能用于添加属性.
No this cannot be done. Reflection is a way of inspecting metadata not mutating it. Hence it cannot be used to add attributes.
此外,程序集中的类型定义,一般来说,是不可变的,不能在运行时改变 [1].这包括向方法添加属性.所以这里也不能使用其他类似反射的技术.
Additionally, type definitions in an assembly, and in general, are immutable and cannot be mutated at runtime [1]. This includes the adding of attributes to a method. So other reflection like technologies cannot be used here either.
[1] ENC 操作是一个例外
[1] The one exception to this is ENC operation
这篇关于我可以将属性与匿名类一起使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我可以将属性与匿名类一起使用吗?
基础教程推荐
- Moq It.Is<>不匹配 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- WPF 模态进度窗口 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
