这是一个带注释的工作示例。 它使用通用的Type of Dictionary和Lambda Func。
using System; using System.Collections.Generic; using System.Linq; namespace ConsoleApplication1 { class Program { // a custom class public class MyPerson { public string FN { get; set; } public string LN { get; set; } } static void Main(string[] args) { // your prebuilt dictionary of Types to Lambda expressions to get a string Dictionary> MyToStringLookup = new Dictionary>() { {typeof(String), new Func( obj => obj.ToString() )}, {typeof(DateTime), new Func( obj => ((DateTime)obj).ToString("d") )}, {typeof(MyPerson), new Func( obj => (obj as MyPerson).LN )}, }; // your list of objects List MyObjects = new List() { "abc123", DateTime.Now, new MyPerson(){ FN = "Bob", LN = "Smith"} }; // how you traverse the list of objects and run the custom ToString foreach (var obj in MyObjects) if (MyToStringLookup.ContainsKey(obj.GetType())) System.Console.WriteLine(MyToStringLookup[obj.GetType()](obj)); else // default if the object doesnt exist in your dictionary System.Console.WriteLine(obj.ToString()); } } }
这样的事情可能会让你在路上:
private static String MyToString(object o) { var val = ""; switch (o.GetType().Name) { case "Boolean": val = ((bool)o) ? "this is true" : "this is false"; break; case "DateTime": val = "The date is: " + ((DateTime)o); break; case "Int32": val = "The number-value is: " + (int)o; break; } return val; }
GetType()。名称有效但会导致您在此上下文中出现潜在错误,因为它可能返回您不知道的类型。 即使一个对象存储为类型A,GetType()。如果BinheritanceA,Name也可能返回“B”。如果你在执行切换的方法的上下文中不知道B(它可能是一个类型另一个inheritance了当前库之一的库,它可能是在你编写方法后添加的类型),你会在伪类型切换中错过它。 如果你写if(obj is A) ,你就不会。
例如,如果我写这个:
/// /// Displays ":)" if obj is a Foo /// public static void CaseType(object obj) { switch(obj.GetType().Name) { case "Foo": MessageBox.Show(":)"); break; default: MessageBox.Show(":("); break; } }
评论是谎言,因为
public class Bar : Foo { } public static void CaseTypeSpecialized() { Foo obj = new Bar(); CaseType(obj); }
将显示“:(”。
如果你写,它会工作
/// /// Displays ":)" if obj is a Foo /// public static void CaseType(object obj) { if (obj is "Foo") { MessageBox.Show(":)"); } else { MessageBox.Show(":("); } }