如何在运行时从类中删除属性
是否可以在运行时从类中删除属性,例如:
public Class A
{
public int num1 {get;set;}
public int num2 {get;set;}
public int num3 {get;set;}
}
Class A Obj = new A();
在运行时我想从 obj
中删除 num2
。是否可以?
Is it possible to remove a property from class at runtime, like:
public Class A
{
public int num1 {get;set;}
public int num2 {get;set;}
public int num3 {get;set;}
}
Class A Obj = new A();
At run time I want to remove num2
from obj
. Is it possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
这是不可能的。编译后,将设置类定义。
This can't be done. Once compiled, a class definition is set.
正如其他人已经说过的,这是不可能的。
相反,您可以添加另一个属性,例如
然后在运行时将 num2 添加到该列表并检查它是否有您应该忽略的属性。
As others said already, it's not possible.
Instead you can add another property e.g.
Then at runtime add
num2
to that list and check it for properties you should ignore.我有一个非常精确的用例。就我而言,我想在通过 Json 将数据模型发布到 ODATA 时忽略一些属性。此属性可能不是表字段,因此我想在将其序列化为 JSON 时忽略它。我通过以下步骤实现了这一点。
ISerializer
创建了一个自定义 JsonSerializer 来忽略 ReadOnly 属性,如下所示:这解决了我忽略某些我不使用的属性的问题不想通过 Json/OData 调用或任何 Api/端点传递,无论它在哪里。
I had a very exact use case. In my case, I want to ignore some properties when posting the data model to ODATA via Json. This property may not be a table field so I want to ignore while serializing this to JSON. I achieved this by below steps.
ISerializer
to ignore the ReadOnly Properties like below:This solved my problem to ignore some properties that I don't want to pass via Json/OData calls or any Api/endpoint wherever it is.
您必须提出模型/视图模型方法。创建一个 ViewModel,该 ViewModel 将具有满足您的要求的有限属性。
You have to comeup with Model/ViewModel approach. Create a ViewModel which will have limited properties for your requirement.
我同意Nic的回复:这是不可能的。编译后,将设置类定义。
但是您可以通过反射动态创建您想要的类属性。
I agree with Nic reply: This can't be done. Once compiled, a class definition is set.
But you can create a class property dynamically what you want by reflection.
我的情况要容易得多
我有一门课是POST
然后我需要删除一些属性并将其保存到 JSON
我确实使用 System.Dynamic.ExpandoObject 复制了类
My case was much easier
I have a class which is POST
then I need to remove few properties and save this to JSON
I did go around with System.Dynamic.ExpandoObject copy the class
我无法删除该属性,我试图创建一个动态 JSON,将 2 个不同的类合并在一起,但没有一些属性(该合并的类不需要),所以我所做的是,我添加了一个自定义属性并添加到我不需要的字段/属性,并在合并 2 个类后使用反射在运行时创建自定义 JSON。
I was not able to REMOVE the property, I was trying to create a dynamic JSON, with 2 different classes merged together but without some properties (not needed for that merged class), so what I did was, I added a custom attribute and added to field/properties which I didn't need, and used reflection to create a custom JSON at runtime after merging 2 classes.