65.9K
CodeProject 正在变化。 阅读更多。
Home

匿名类型 - C# 中的动态编程

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.20/5 (5投票s)

2009 年 7 月 27 日

CC (ASA 2.5)

2分钟阅读

viewsIcon

39283

downloadIcon

215

匿名类型是 .NET 语言中一个强大的特性,但在需要传递这些信息时会受到限制。 在本文中,我将讨论我编写的一个类,它允许您轻松地使用匿名类型,即使它们离开了初始作用域。

引言

您是否尝试过在 C# 中传递匿名类型? 这并不是很好用,因为一旦您的类型失去了作用域,就无法再次将其转换为正确的类型(至少不容易)。 在本文中,我将讨论我编写的一个类,它允许您轻松地使用匿名类型,即使它们离开了初始作用域。

更简单的方法

之前的文章中,我讨论了尝试在 .NET 中使用匿名类型。 我 包含了一些用于处理这些类型的代码,以尝试使在您的项目中传递信息更容易。

本质上,它是一个反射的包装器,允许您通过提供正确的类型和属性名称来访问属性。 它会将匿名类型的实例保存在内存中,以便可以直接与对象一起使用。

您可能已经注意到,存在 .Get() 函数,但没有 .Set() 函数。 为什么会这样?

您可能以前从未注意到这一点,但匿名类型中的所有属性都是只读的。 大多数情况下,您不会更改这些值,但如果您无法在一次传递中分配属性的值,那将会很麻烦。

进一步扩展

为了好玩,我花了一些时间编写了 AnonymousType 的另一个版本。 这个版本比之前的版本更灵活,但您实际上并没有以 C# 应该被使用的正确方式来使用它。 您没有使用反射,而是使用 Dictionary,特别是使用字符串(用于属性名称)和对象(用于值)。

您以与之前相同的方式创建对象,但现在您可以使用更多功能和函数。 以下是一些**使用此类的示例**。

//Creating Instances of AnonymousType
//==============================
//Create a using an Anonymous type
AnonymousType type = AnonymousType.Create(new {
  name = "Jim",
  age = 40
  //method = ()=> { Console.WriteLine(); } // still doesn't work here
});

//or an empty AnonymousType
AnonymousType empty = new AnonymousType();

//or even an existing object
var something = new {
  name = "Mark",
  age = 50
};
AnonymousType another = new AnonymousType(something);


//Creating And Using Methods
//==============================
//append methods and call them
another.SetMethod("print", (string name, int age, bool admin) => {
  Console.WriteLine("{0} :: {1} :: {2}", name, age, admin);
});
another.Call("print", "Mark", 40, false);

//append a method with a return value
another.SetMethod("add", (int a, int b) => {
  return a + b;
});
int result = another.Call<int>("add", 5, 10);


//Working With Multiple Properties
//==============================
//add properties and work with them
//(NOTE: a better way is shown below)
another.Set("list", new List<string>());
another.Get<List<string>>("list").Add("String 1");
another.Get<List<string>>("list").Add("String 2");
another.Get<List<string>>("list").Add("String 3");

//or use it an easier way
another.With((List<string> list) => {
  list.Add("String 4");
  list.Add("String 5");
  list.Add("String 6");
});

//you can work with more than one type
another.With((string name, int age) => {
  Console.Write("{0} :: {1}", name, age);
});

再次说明,这偏离了 C# 应该被使用的正确方式,因此请谨慎使用。 在大多数情况下,您需要创建自己的类来保存这些信息,但在使用匿名类型时,这是一种快速简便的方法来传递您的信息。

敬请期待第三版(一些非常酷的东西!)

源代码

© . All rights reserved.