泛型约束和利用反射修改对象属性的值

周日了都,昨天休息了一天,今天想想得敲敲代码练习一下,如下关于泛型约束和利用反射修改对象属性的值的,

都挺简单的,呵呵,但时间一长,不经常使用还容易忘记在此就当记录一下了,

首先泛型代码一般是如下的情形:

加了泛型约束,只允许引用类型并且是只能是无参数的构造函数的类型才能传入,也就是不允许给类构造参数传递实参,否则将报错。

错误 1 “XXXXXX.pros”必须是具有公共的无参数构造函数的非抽象类型,才能用作泛型类型或方法“

 1    public static T GetObject<T>(T Object) where T:class,new ()
 2         {
 3             string temp = string.Empty;
 4             System.Reflection.PropertyInfo[] propertyinfo = Object.GetType().GetProperties();
 5             foreach (System.Reflection.PropertyInfo p in propertyinfo)
 6             {
 7                 if (p.PropertyType == typeof(string))
 8                 {
 9                     temp = p.GetValue(Object, null).ToString();
10                     p.SetValue(Object, temp + temp.Length, null);
11                 }
12             }
13             return Object;
14 
15         }
View Code

那解决办法就是在类中显示声明无参构造函数

 1   class pros
 2     {
 3         public pros(string  s) {
 4 
 5 
 6             Console.WriteLine(s);
 7         }
 8         public pros() { }//无参构造函数
 9  
10         public string demoStr { set; get; }
11     }
12     class Program
13      {
14         static void Main(string[] args)
15         {
16          
17              
18 
19             pros pro = new pros("s") { demoStr = "ss" };
20             pros p = GetObject(pro);
21             Console.WriteLine(p.demoStr);
22 
23             Console.ReadKey(true);
24 
25         }
26 
27         public static T GetObject<T>(T Object) where T:class,new ()
28         {
29             string temp = string.Empty;
30             System.Reflection.PropertyInfo[] propertyinfo = Object.GetType().GetProperties();
31             foreach (System.Reflection.PropertyInfo p in propertyinfo)
32             {
33                 if (p.PropertyType == typeof(string))
34                 {
35                     temp = p.GetValue(Object, null).ToString();
36                     p.SetValue(Object, temp + temp.Length, null);
37                 }
38             }
39             return Object;
40 
41         }
42      }
View Code
原文地址:https://www.cnblogs.com/scien626/p/4492749.html