是否有方法将属性设置为匿名类型属性?

时间:2022-11-27 14:30:45

Is there a way you can put attributes on properties in an anonymous type? Or the anonymous type itself? If not when you create it, perhaps afterwards via reflection?

是否有一种方法可以将属性放在匿名类型的属性上?还是匿名类型本身?如果不是,当你创建它时,也许之后通过反射?

As a potential use scenario, let me borrow from Dapper:

作为一种潜在的使用场景,让我向Dapper借用一下:

When providing parameters to execute a query in Dapper, you provide the parameters in an anonymous type:

当您在Dapper中提供执行查询的参数时,您提供的参数是匿名类型的:

connection.Query<Foo>(sql, new { Id = guid, Condition = true });

Let's say I needed to communicate something about mapping like maybe we store booleans as text T/F (horrible, but sadly true to real-life experience), so I want to add an attribute to that Condition property to tell Dapper how to map it (again this is a slightly forced example). Is that possible?

假设我需要传递一些关于映射的信息,比如我们可能将布尔值存储为文本T/F(很糟糕,但不幸的是真实的真实体验),所以我想给条件属性添加一个属性,告诉Dapper如何映射它(同样这是一个有点勉强的例子)。这有可能吗?

1 个解决方案

#1


6  

No, you can't do this either at the point of declaration or afterwards with reflection.

不,你不能在声明的时候或者在事后进行反思。

The closest you could come would be to use an existing anonymous type as the basis for a new type created with CodeDom, or maybe Mono Cecil.

最接近的可能是使用一个现有的匿名类型作为使用CodeDom创建的新类型的基础,或者可能是Mono Cecil。

I suspect you'd be better off just writing the code manually yourself instead.

我怀疑你最好自己手工编写代码。

#1


6  

No, you can't do this either at the point of declaration or afterwards with reflection.

不,你不能在声明的时候或者在事后进行反思。

The closest you could come would be to use an existing anonymous type as the basis for a new type created with CodeDom, or maybe Mono Cecil.

最接近的可能是使用一个现有的匿名类型作为使用CodeDom创建的新类型的基础,或者可能是Mono Cecil。

I suspect you'd be better off just writing the code manually yourself instead.

我怀疑你最好自己手工编写代码。