如何从C#中的对象中删除属性及其值 [英] How to remove property and its value from object in C#

查看:2144
本文介绍了如何从C#中的对象中删除属性及其值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有一些属性的类

如何从该对象中删除具有null的特定属性。

I have a class with some properties
How to remove specific properties from that object which has null.

Class A
{ public int id{get;set;}public string name{get;set;}public string address{get;set;} 


  obj=  GetAList(id);//This will store the one record





所以我想从对象中删除null属性



我尝试过:





So i want to remove null property from the object

What I have tried:

How  to remove specific  properties from that object which has null.

推荐答案

你不能。当它为null时忽略它,如下所示:

You can't. Just ignore it when it is null, something like this:
if (obj.propertyname != null )
{
  // do something
}


这取决于你的意思删除。出于什么目的?基于给出的非常有限的信息:



1.如果你想要实际删除它,那么Peter的答案就是解决方案。



2.您可以使用Linq并转换为动态类型...



3.如果您在申请中谈论或暴露从库中,您可以使用封装。使用您想要公开的属性/方法创建另一个类,并复制/包装原始类。



4.如果您正在谈论序列化,那么那里是选择。这些选项取决于什么类型的序列化 - CSV,二进制,Json,Xml等......它们都不同。



我肯定但是还有其他可能性,这个问题并没有给出你想要实现的目标的充分理解。
It depends on what you mean by remove. For what purpose? Based on the very limited information given:

1. If you want to physically remove it, then Peter's answer is the solution.

2. You could use Linq and cast to a dynamic type...

3. If you are talking about within your application or exposing from a library, you could use encapsulation. Create another class with just the properties/methods that you want to expose and copy/wrap the original class.

4. If you're talking about serialization, then there are options. What those options are depends on what type of serialization is being done - CSV, binary, Json, Xml, etc... They are all different.

I am sure that there are other possibilities however the question does not give enough of an idea of what you are attempting to achieve.


这篇关于如何从C#中的对象中删除属性及其值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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