C#返回object对象的指定属性

以object类型的对象返回其Shape属性为例。

        /// <summary>
        /// 返回Object对象的指定属性
        /// </summary>
        /// <param name="obj">传入的对象</param>
        /// <returns>返回的属性</returns>
        private GeoJSON.Net.Geometry.Point GetShape(object obj)
        {
            System.Reflection.PropertyInfo a = null;
            foreach (System.Reflection.PropertyInfo pi in obj.GetType().GetProperties())
            {
                if (pi.CanWrite)
                {
                    if (0 == string.Compare("Shape", pi.Name, true))
                    {
                        a = pi;
                        break;
                    }
                }
            }
            if (null == a)
            {
                return null;
            }
            return a.GetValue(obj) as GeoJSON.Net.Geometry.Point;
        }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要判断一个对象集合是否包含某个属性,可以使用 LINQ 查询语句和反射来实现。具体实现步骤如下: 1. 使用 LINQ 查询语句从对象集合中筛选出包含指定属性对象。 2. 使用反射获取对象属性列表。 3. 遍历对象集合中的每个对象,判断对象是否包含指定属性。 4. 如果对象包含指定属性,则返回 true,否则返回 false。 以下是示例代码: ```csharp using System; using System.Collections.Generic; using System.Linq; using System.Reflection; class Program { static void Main(string[] args) { List<Person> people = new List<Person> { new Person { Name = "Alice", Age = 28 }, new Person { Name = "Bob", Age = 30 }, new Person { Name = "Charlie", Age = 35 }, }; bool hasAge = HasProperty(people, "Age"); Console.WriteLine("Has Age property: " + hasAge); bool hasGender = HasProperty(people, "Gender"); Console.WriteLine("Has Gender property: " + hasGender); Console.ReadKey(); } static bool HasProperty(IEnumerable<object> collection, string propertyName) { var type = collection.GetType().GetGenericArguments()[0]; var properties = type.GetProperties(); return properties.Any(p => p.Name == propertyName); } } class Person { public string Name { get; set; } public int Age { get; set; } } ``` 在上面的示例中,我们定义了一个包含 Name 和 Age 两个属性的 Person 类,并创建了一个包含三个 Person 对象的 List。然后,我们分别判断该 List 是否包含 Age 和 Gender 两个属性。最终输出结果为: ``` Has Age property: True Has Gender property: False ``` 可以看到,HasProperty 方法可以判断对象集合是否包含指定属性

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值