首页 / C#开发 / 正文

C#/.NET应用程序编程开发中如何判断一个对象是否为匿名对象?

4959 发布于: 2019-06-13 读完约需7分钟

问题描述

如题,在C#/.NET应用程序编程开发中创建一个对象的方式有多种,可以首先定义一个特定的类,然后new实例化,另外还可以创建匿名对象。开发过程中,有时候需要判断当前的对象是否为匿名对象,应该如何实现呢?

方案一

在解决这个问题之前,我们应该首先整理一下关于C#匿名对象具有的特性,这样才能更好地对是否是匿名对象的判断提供依据。在解决问题的时候尽量做到“知其然,知其所以然”。

判断匿名对象的主要依据有:

  • 任何的C#匿名类型均直接派生自System.Object基类,同时C#匿名类型还是一个密封类。因此,C#匿名类型的属性是只读的,也就意味着当匿名类型被初始化后就不能修改属性的值了
  • 一个C#匿名类型可以包含一个或者多个属性
  • C#匿名对象不能包含类型的成员,如:事件,方法等等
  • C#匿名对象用于初始化属性值的表达式不能是null,或者匿名方法,或者一个指针类型
  • C#匿名对象是引用类型
  • C#匿名对象是泛型的,具有和属性一样多的类型参数
  • C#匿名对象的每个属性都是公共的
  • C#匿名对象被属性类CompilerGeneratedAttribute修饰
  • C#匿名对象的名称中包含AnonymousType字符串
  • C#匿名对象的名称以<>开始

在了解了C#匿名对象的诸多特性之后,我们就可以使用这些特性来编写判断是否为匿名对象的方法了,如:

private static bool CheckIfAnonymousType(Type type)
{
  if (type == null)
      throw new ArgumentNullException("type");

  return Attribute.IsDefined(type, typeof(CompilerGeneratedAttribute), false)
      && type.IsGenericType && type.Name.Contains("AnonymousType")
      && (type.Name.StartsWith("<>"))
      && (type.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic;
}

完整的示例代码如下:

using System;
using System.Runtime.CompilerServices;
using System.Reflection;

public class Program
{
  public static void Main()
  {
    var anonymousCustomer = new {Id=1,Name="Rector"};
    Console.WriteLine("anonymousCustomer is anonymous type: {0}",CheckIfAnonymousType(anonymousCustomer.GetType()));

    var classCustomer = new Customer {Id=1,Name="Rector"};
    Console.WriteLine("classCustomer is anonymous type: {0}",CheckIfAnonymousType(classCustomer.GetType()));
  }

  private static bool CheckIfAnonymousType(Type type)
  {
      if (type == null)
          throw new ArgumentNullException("type");

      return Attribute.IsDefined(type, typeof(CompilerGeneratedAttribute), false)
          && type.IsGenericType && type.Name.Contains("AnonymousType")
          && (type.Name.StartsWith("<>"))
          && (type.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic;
  }
}


public class Customer
{
  public int Id {get;set;}
  public string Name {get;set;}
}

输出结果为:

anonymousCustomer is anonymous type: True
classCustomer is anonymous type: False

请注意分别引用命名空间System.Runtime.CompilerServicesSystem.Reflection

版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。

上一篇: C#匿名类型详解--什么是C#匿名类型?C#匿名类型有哪些特征?

下一篇: C#/.NET应用程序编程开发中如何获取当前类的类名?

本文永久链接码友网 » C#/.NET应用程序编程开发中如何判断一个对象是否为匿名对象?

分享扩散:

发表评论

登录用户才能发表评论, 请 登 录 或者 注册