我可以将属性与匿名类一起使用吗?

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

这篇关于我可以将属性与匿名类一起使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:我可以将属性与匿名类一起使用吗?

基础教程推荐