标签:
1 DateTime dt = new DateTime(); 2 Type type = dt.GetType(); 3 foreach (System.Reflection.PropertyInfo property in type.GetProperties()) 4 { 5 Console.WriteLine(property.Name); 6 } 7 Console.ReadLine();
1 using System.Diagnostics; 2 3 ThreadPriorityLevel priority = 4 (ThreadPriorityLevel)Enum.Parse(typeof(ThreadPriorityLevel), "Idle");
1 using System; 2 using System.Diagnostics; 3 using System.Reflection; 4 5 namespace ConsoleApplication2 6 { 7 class Program 8 { 9 static void Main(string[] args) 10 { 11 12 13 string[] commadnstr = new string[] { "Comparess.exe", "/Out:newFile", ": <file name>", "/Help:true", "/test:testquestion" }; 14 string errorMessage; 15 CommandLineInfo commandLine = new CommandLineInfo(); 16 17 if (!CommandLinHanlder.TryParse(commadnstr, commandLine, out errorMessage)) 18 { 19 Console.WriteLine(errorMessage); 20 DisplayHelp(); 21 22 } 23 if (commandLine.Help) 24 { 25 DisplayHelp(); 26 } 27 else 28 { 29 if (commandLine.Proiroity != ProcessPriorityClass.Normal) 30 { 31 //Change thread priority 32 } 33 } 34 Console.ReadLine(); 35 } 36 private static void DisplayHelp() 37 { 38 //Display the command-Line help. 39 } 40 41 private class CommandLineInfo 42 { 43 public bool Help { get; set; } 44 public string Out { get; set; } 45 private ProcessPriorityClass _priority = ProcessPriorityClass.Normal; 46 public ProcessPriorityClass Proiroity 47 { 48 get { return _priority; } 49 set { _priority = value; } 50 } 51 52 } 53 } 54 55 public class CommandLinHanlder 56 { 57 public static void Parse(string[] args, object commandLine) 58 { 59 string errorMessage; 60 if (!TryParse(args, commandLine, out errorMessage)) 61 { 62 throw new ApplicationException(errorMessage); 63 } 64 65 66 } 67 public static bool TryParse(string[] args, object commandLine, out string errorMessage) 68 { 69 bool success = false; 70 errorMessage = null; 71 foreach (string arg in args) 72 { 73 string option; 74 if (arg[0] == ‘/‘ || arg[0] == ‘-‘) 75 { 76 string[] optionParts = arg.Split(new char[] { ‘:‘ }, 2); 77 //Remove the slash/dash 除去 / 和 - 78 option = optionParts[0].Remove(0, 1).Trim(); 79 optionParts[1] = optionParts[1].Trim(); 80 81 PropertyInfo property = 82 commandLine.GetType().GetProperty(option, 83 BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public);//根据输入的字符串,获取对应的属性 84 85 if (property != null)//判断输入的有无 86 { 87 //根据属性数据类型 调用SetValue为属性set设置值 88 if (property.PropertyType == typeof(bool)) 89 { 90 property.SetValue(commandLine, true, null); 91 success = true; 92 } 93 else if (property.PropertyType == typeof(string)) 94 { 95 property.SetValue(commandLine, optionParts[1], null); 96 success = true; 97 } 98 else if (property.PropertyType.IsEnum) 99 { 100 //枚举类型的设置,以及报错处理 101 try 102 { 103 property.SetValue(commandLine, 104 Enum.Parse( 105 typeof(ProcessPriorityClass), optionParts[1], true) 106 , null); 107 success = true; 108 } 109 catch (ArgumentException) 110 { 111 success = false; 112 errorMessage = string.Format("The option ‘{0}‘ is invalid for ‘{1}‘" 113 , optionParts[1], option); 114 } 115 } 116 else 117 { 118 //不被支持的属性数据类型 119 success = false; 120 errorMessage = string.Format("Data type ‘{0}‘ on {1} is not supported", 121 property.PropertyType.ToString(), 122 commandLine.GetType().ToString()); 123 } 124 } 125 else 126 { 127 //不支持的命令行选项,没有此相关属性 128 success = false; 129 errorMessage = string.Format("Option ‘{0}‘ is not supported.", option); 130 } 131 132 133 } 134 135 136 } 137 return success; 138 } 139 } 140 141 }
1 public class Stack<T> 2 { 3 public void Add(T i) 4 { 5 Type t = typeof(T); 6 } 7 }
1 Type type; 2 type = typeof(System.Nullable<>); 3 Console.WriteLine(type.ContainsGenericParameters); 4 Console.WriteLine(type.IsGenericType); 5 6 type = typeof(System.Nullable<DateTime>); 7 Console.WriteLine(type.ContainsGenericParameters); 8 Console.WriteLine(type.IsGenericType);
1 Stack<int> s = new Stack<int>(); 2 Type t = s.GetType(); 3 4 foreach (Type type in t.GetGenericArguments()) 5 { 6 Console.WriteLine("Type parameter:" + type.FullName); 7 }
1 class CommandLineInfo 2 { 3 [CommandLineSwitchAlias("?")] 4 public bool Help 5 { 6 get { return _Help; } 7 set { _Help = value; } 8 } 9 private bool _Help; 10 11 [CommandLineSwitchRequired] 12 public string Out 13 { 14 get { return _Out; } 15 set { _Out = value; } 16 } 17 private string _Out; 18 19 public System.Diagnostics.ProcessPriorityClass Priority 20 { 21 get { return _Priority; } 22 set { _Priority = value; } 23 } 24 private System.Diagnostics.ProcessPriorityClass _Priority = 25 System.Diagnostics.ProcessPriorityClass.Normal; 26 } 27 28 internal class CommandLineSwitchRequiredAttribute : Attribute 29 { 30 //not implimented 31 } 32 33 internal class CommandLineSwitchAliasAttribute : Attribute 34 { 35 public CommandLineSwitchAliasAttribute(string s) 36 { 37 //not implimented 38 } 39 }
1 //Two Ways to do it 2 //[CommandLineSwitchRequired] 3 //[CommandLineSwitchAlias("FileName")] 4 [CommandLineSwitchRequired, 5 CommandLineSwitchAlias("FileName")] 6 public string Out 7 { 8 get { return _Out; } 9 set { _Out = value; } 10 }
1 using System.Reflection; 2 using System.Runtime.CompilerServices; 3 using System.Runtime.InteropServices; 4 5 // General Information about an assembly is controlled through the following 6 // set of attributes. Change these attribute values to modify the information 7 // associated with an assembly. 8 [assembly: AssemblyTitle("Chapter17")] 9 [assembly: AssemblyDescription("")] 10 [assembly: AssemblyConfiguration("")] 11 [assembly: AssemblyCompany("")] 12 [assembly: AssemblyProduct("Chapter17")] 13 [assembly: AssemblyCopyright("Copyright ? 2010")] 14 [assembly: AssemblyTrademark("")] 15 [assembly: AssemblyCulture("")] 16 17 // Setting ComVisible to false makes the types in this assembly not visible 18 // to COM components. If you need to access a type in this assembly from 19 // COM, set the ComVisible attribute to true on that type. 20 [assembly: ComVisible(false)] 21 22 // The following GUID is for the ID of the typelib if this project is exposed to COM 23 [assembly: Guid("9adaf385-f1a3-474f-8a36-5c059a7a7e22")] 24 25 // Version information for an assembly consists of the following four values: 26 // 27 // Major Version 28 // Minor Version 29 // Build Number 30 // Revision 31 // 32 // You can specify all the values or you can default the Build and Revision Numbers 33 // by using the ‘*‘ as shown below: 34 // [assembly: AssemblyVersion("1.0.*")] 35 [assembly: AssemblyVersion("1.0.0.0")] 36 [assembly: AssemblyFileVersion("1.0.0.0")] 37 38 return:特性,出现在一个方法声明之前。 39 using System.ComponentModel; 40 41 public class Program 42 { 43 [return: Description( 44 "Returns true if the object is in a valid state.")] 45 public bool IsValid() 46 { 47 // ... 48 return true; 49 } 50 }
1 public class CommandLineSwitchRequiredAttribute : System.Attribute 2 { 3 4 } 5
1 public class CommandLineSwitchRequiredAttribute : Attribute 2 { 3 public static string[] GetMissingRequiredOptions( 4 object commandLine) 5 { 6 List<string> missingOptions = new List<string>(); 7 PropertyInfo[] properties = 8 commandLine.GetType().GetProperties(); 9 10 foreach (PropertyInfo property in properties) 11 { 12 Attribute[] attributes = 13 (Attribute[])property.GetCustomAttributes( 14 typeof(CommandLineSwitchRequiredAttribute), 15 false); 16 if ((attributes.Length > 0) && 17 (property.GetValue(commandLine, null) == null)) 18 { 19 missingOptions.Add(property.Name); 20 } 21 } 22 return missingOptions.ToArray(); 23 } 24 }
1 public class CommandLineSwitchAliasAttribute : Attribute 2 { 3 public CommandLineSwitchAliasAttribute(string alias) 4 { 5 Alias = alias; 6 } 7 public string Alias 8 { 9 get { return _Alias; } 10 set { _Alias = value; } 11 } 12 private string _Alias; 13 } 14 class CommandLineInfo 15 { 16 [CommandLineSwitchAlias("?")] 17 public bool Help 18 { 19 get { return _Help; } 20 set { _Help = value; } 21 } 22 private bool _Help; 23 24 // ... 25 }
1 PropertyInfo property = 2 typeof(CommandLineInfo).GetProperty("Help"); 3 CommandLineSwitchAliasAttribute attribute = 4 (CommandLineSwitchAliasAttribute) 5 property.GetCustomAttributes( 6 typeof(CommandLineSwitchAliasAttribute), false)[0]; 7 if (attribute.Alias == "?") 8 { 9 Console.WriteLine("Help(?)"); 10 }; 11 }
1 public class CommandLineSwitchAliasAttribute : Attribute 2 { 3 public CommandLineSwitchAliasAttribute(string alias) 4 { 5 Alias = alias; 6 } 7 8 public string Alias 9 { 10 get { return _Alias; } 11 set { _Alias = value; } 12 } 13 private string _Alias; 14 15 public static Dictionary<string, PropertyInfo> GetSwitches( 16 object commandLine) 17 { 18 PropertyInfo[] properties = null; 19 Dictionary<string, PropertyInfo> options = 20 new Dictionary<string, PropertyInfo>(); 21 22 properties = commandLine.GetType().GetProperties( 23 BindingFlags.Public | BindingFlags.NonPublic | 24 BindingFlags.Instance); 25 foreach (PropertyInfo property in properties) 26 { 27 options.Add(property.Name.ToLower(), property); 28 foreach (CommandLineSwitchAliasAttribute attribute in 29 property.GetCustomAttributes( 30 typeof(CommandLineSwitchAliasAttribute), false)) 31 { 32 options.Add(attribute.Alias.ToLower(), property); 33 } 34 } 35 return options; 36 } 37 }
1 public class CommandLineHandler 2 { 3 // ... 4 public static bool TryParse( 5 string[] args, object commandLine, 6 out string errorMessage) 7 { 8 bool success = false; 9 errorMessage = null; 10 11 Dictionary<string, PropertyInfo> options = 12 CommandLineSwitchAliasAttribute.GetSwitches( 13 commandLine); 14 15 foreach (string arg in args) 16 { 17 PropertyInfo property; 18 string option; 19 if (arg[0] == ‘/‘ || arg[0] == ‘-‘) 20 { 21 string[] optionParts = arg.Split( 22 new char[] { ‘:‘ }, 2); 23 option = optionParts[0].Remove(0, 1).ToLower(); 24 25 if (options.TryGetValue(option, out property)) 26 { 27 success = SetOption( 28 commandLine, property, 29 optionParts, ref errorMessage); 30 } 31 else 32 { 33 success = false; 34 errorMessage = string.Format( 35 "Option ‘{0}‘ is not supported.", 36 option); 37 } 38 } 39 } 40 return success; 41 } 42 43 private static bool SetOption( 44 object commandLine, PropertyInfo property, 45 string[] optionParts, ref string errorMessage) 46 { 47 bool success; 48 49 if (property.PropertyType == typeof(bool)) 50 { 51 // Last parameters for handling indexers 52 property.SetValue( 53 commandLine, true, null); 54 success = true; 55 } 56 else 57 { 58 59 if ((optionParts.Length < 2) 60 || optionParts[1] == "" 61 || optionParts[1] == ":") 62 { 63 // No setting was provided for the switch. 64 success = false; 65 errorMessage = string.Format( 66 "You must specify the value for the {0} option.", 67 property.Name); 68 } 69 else if ( 70 property.PropertyType == typeof(string)) 71 { 72 property.SetValue( 73 commandLine, optionParts[1], null); 74 success = true; 75 } 76 else if (property.PropertyType.IsEnum) 77 { 78 success = TryParseEnumSwitch( 79 commandLine, optionParts, 80 property, ref errorMessage); 81 } 82 else 83 { 84 success = false; 85 errorMessage = string.Format( 86 "Data type ‘{0}‘ on {1} is not supported.", 87 property.PropertyType.ToString(), 88 commandLine.GetType().ToString()); 89 } 90 } 91 return success; 92 } 93 94 private static bool TryParseEnumSwitch(object commandLine, string[] optionParts, PropertyInfo property, ref string errorMessage) 95 { 96 throw new NotImplementedException(); 97 } 98 }
1 [AttributeUsage(AttributeTargets.Property)] 2 public class CommandLineSwitchAliasAttribute : Attribute 3 { 4 // ... 5 }
1 // Restrict the attribute to properties and methods 2 [AttributeUsage( 3 AttributeTargets.Field | AttributeTargets.Property)] 4 public class CommandLineSwitchAliasAttribute : Attribute 5 { 6 // ... 7 }
1 [AttributeUsage(AttributeTargets.Property, AllowMultiple = true)] 2 public class CommandLineSwitchAliasAttribute : Attribute 3 { 4 // ... 5 }
1 using System; 2 using System.IO; 3 4 class Program 5 { 6 public static void Main() 7 { 8 // ... 9 string fileName = @"enumtest.txt"; 10 FileInfo file = new FileInfo(fileName); 11 12 file.Attributes = FileAttributes.Hidden | 13 FileAttributes.ReadOnly; 14 15 Console.WriteLine("\"{0}\" outputs as \"{1}\"", 16 file.Attributes.ToString().Replace(",", " |"), 17 file.Attributes); 18 19 FileAttributes attributes = 20 (FileAttributes)Enum.Parse(typeof(FileAttributes), 21 file.Attributes.ToString()); 22 23 Console.WriteLine(attributes); 24 25 // ... 26 } 27 }
1 #define CONDITION_A 2 using System; 3 using System.Diagnostics; 4 using System.Reflection; 5 using System.Collections.Generic; 6 7 8 namespace ConsoleApplication2 9 { 10 public class Program 11 { 12 public static void Main() 13 { 14 Console.WriteLine("Begin..."); 15 MethodA(); 16 MethodB(); 17 Console.WriteLine("End..."); 18 } 19 20 [Conditional("CONDITION_A")] 21 static void MethodA() 22 { 23 Console.WriteLine("MethodA() executing..."); 24 } 25 26 [Conditional("CONDITION_B")] 27 static void MethodB() 28 { 29 Console.WriteLine("MethodB() executing..."); 30 } 31 } 32 }
1 class Program 2 { 3 public static void Main() 4 { 5 ObsoleteMethod(); 6 } 7 8 [Obsolete] 9 public static void ObsoleteMethod()//if you look through the warnings in the error list the warning will also show up in that list 10 { 11 } 12 }
1 [Obsolete("建议使用NewMethod()")] 2 public static void ObsoleteMethod()//if you look through the warnings in the error list the warning will also show up in that list 3 { 4 }
1 using System; 2 using System.IO; 3 using System.Runtime.Serialization.Formatters.Binary; 4 5 6 namespace ConsoleApplication2 7 { 8 class Program 9 { 10 public static void Main() 11 { 12 Stream stream; 13 Document documentBefore = new Document(); 14 documentBefore.Title = "before"; 15 documentBefore.Data = "this is a data"; 16 Document documentAfter; 17 //序列化 18 using (stream = File.Create(Environment.CurrentDirectory+"\\"+ documentBefore.Title + ".bin")) 19 { 20 BinaryFormatter formatter = new BinaryFormatter(); 21 formatter.Serialize(stream, documentBefore); 22 } 23 24 //反序列化 25 using (stream = File.Open(Environment.CurrentDirectory + "\\" + documentBefore.Title + ".bin", FileMode.Open)) 26 { 27 BinaryFormatter formatter = new BinaryFormatter(); 28 documentAfter = (Document)formatter.Deserialize(stream); 29 } 30 } 31 32 33 34 } 35 [Serializable] 36 class Document 37 { 38 public string Title = null; 39 public string Data = null; 40 41 [NonSerialized] 42 public long _WindowHandle = 0; 43 class Image 44 { 45 } 46 [NonSerialized] 47 private Image Picture = new Image(); 48 } 49 }
1 using System; 2 using System.Runtime.Serialization; 3 [Serializable] 4 class EncryptableDocument : ISerializable 5 { 6 enum Field 7 { 8 Title, 9 Data 10 } 11 public string Title; 12 public string Data; 13 14 public static string Ecrypt(string data) 15 { 16 string encryptedData = data; 17 //加密算法 18 return encryptedData; 19 } 20 public static string Decrypt(string encryptedData) 21 { 22 string data = encryptedData; 23 //解密算法 24 return data; 25 } 26 27 #region 序列化与反序列化 28 public void GetObjectData(SerializationInfo info, StreamingContext context) 29 { 30 info.AddValue(Field.Title.ToString(), Title);//name value 键值对 31 info.AddValue(Field.Data.ToString(), Ecrypt(Data)); 32 } 33 34 //用序列化后的数据来构造 35 public EncryptableDocument(SerializationInfo info, StreamingContext context) 36 { 37 Title = info.GetString(Field.Title.ToString()); 38 Data = Decrypt(info.GetString(Field.Data.ToString())); 39 40 } 41 #endregion 42 }
dynamic data = "Hello World"; Console.WriteLine(data); data = 2 * 100+data.Length; Console.WriteLine(data); data = true; Console.WriteLine(data);
1 XElement person = XElement.Parse( 2 @"<Person> 3 <FirstName>Inigo</FirstName> 4 <LastName>Montoya</LastName> 5 </Person>"); 6 7 Console.WriteLine("{0} {1}", 8 person.Element("FirstName").Value, 9 person.Element("LastName").Value);
1 dynamic person = DynamicXml.Parse( 2 @"<Person> 3 <FirstName>Inigo</FirstName> 4 <LastName>Montoya</LastName> 5 </Person>"); 6 7 Console.WriteLine("{0} {1}", 8 person.FirstName, person.LastName);
1 public class DynamicXml : DynamicObject 2 { 3 private XElement Element { get; set; } 4 5 public DynamicXml(System.Xml.Linq.XElement element) 6 { 7 Element = element; 8 } 9 10 public static DynamicXml Parse(string text) 11 { 12 return new DynamicXml(XElement.Parse(text)); 13 } 14 //调用成员时会调用此方法,如: person.FirstName 15 public override bool TryGetMember( 16 GetMemberBinder binder, out object result) 17 { 18 bool success = false; 19 result = null; 20 XElement firstDescendant = 21 Element.Descendants(binder.Name).FirstOrDefault(); 22 if (firstDescendant != null) 23 { 24 if (firstDescendant.Descendants().Count() > 0) 25 { 26 result = new DynamicXml(firstDescendant); 27 } 28 else 29 { 30 result = firstDescendant.Value; 31 } 32 success = true; 33 } 34 return success; 35 } 36 //设置成员值时会调用,如: person.FirstName = "text"; 37 public override bool TrySetMember( 38 SetMemberBinder binder, object value) 39 { 40 bool success = false; 41 XElement firstDescendant = 42 Element.Descendants(binder.Name).FirstOrDefault(); 43 if (firstDescendant != null) 44 { 45 if (value.GetType() == typeof(XElement)) 46 { 47 firstDescendant.ReplaceWith(value); 48 } 49 else 50 { 51 firstDescendant.Value = value.ToString(); 52 } 53 success = true; 54 } 55 return success; 56 } 57 }
标签:
原文地址:http://www.cnblogs.com/tlxxm/p/4675087.html