如何在 C# 中迭代​​对象的所有属性? [英] How to iterate on all properties of an object in C#?

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

问题描述

我是 C# 新手,我想编写一个函数来迭代对象的属性并将所有空字符串设置为".我听说可以使用称为反射"的东西,但我不知道如何使用.

I am new to C#, I want to write a function to iterate over properties of an object and set all null strings to "". I have heard that it is possible using something called "Reflection" but I don't know how.

谢谢

推荐答案

public class Foo
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
    public int Prop3 { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var foo = new Foo();

        // Use reflection to get all string properties 
        // that have getters and setters
        var properties = from p in typeof(Foo).GetProperties()
                         where p.PropertyType == typeof(string) &&
                               p.CanRead &&
                               p.CanWrite
                         select p;

        foreach (var property in properties)
        {
            var value = (string)property.GetValue(foo, null);
            if (value == null)
            {
                property.SetValue(foo, string.Empty, null);
            }
        }

        // at this stage foo should no longer have null string properties
    }
}

这篇关于如何在 C# 中迭代​​对象的所有属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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