我可以使用属性与匿名类? [英] Can I use Attributes with Anonymous classes?

查看:116
本文介绍了我可以使用属性与匿名类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个匿名类:

  VAR someAnonymousClass =新
{
    SomeInt = 25,
    SomeString =你好匿名类!
    SomeDate = DateTime.Now
};

反正是有属性附加到这个类?反思,其他的?我真的希望这样的事情:

  VAR someAnonymousClass =新
{
    [MyAttribute()]
    SomeInt = 25,
    SomeString =你好匿名类!
    SomeDate = DateTime.Now
};


解决方案

您实际上正在创建的内容在此被称为匿名类型,而不是动态的。

可惜没有就没有办法实现你正在尝试做的。匿名类型都意味着是一个很简单的不可变的类型包括名称/值对。

匿名类型的C#版本只允许您自定义设置的名称/值对底层类型。没有其他的。 VB.Net允许的对可以是可变的或不可变的稍微定制。无论是让你增加,虽然与属性的类型。

如果你想添加你需要创建一个完整的类型的属性。

修改 OP问的特性,可能会通过反射来添加。

没有这个不能这样做。反思是检查元数据不是变异它的方式。因此,它不能被用于添加属性。

此外,在装配式定义,并在一般情况下,是不可变的,并且不能在运行时被突变[1]。这包括属性的增加的方法。因此,像其他的技术反映不能在这里无论是使用。

[1]的一个例外,这是ENC操作

I have a anonymous class:

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.

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 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.

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] The one exception to this is ENC operation

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆