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

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

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

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

错误 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

相关文章:

  • 2021-10-09
  • 2021-07-21
  • 2021-05-18
  • 2021-08-21
  • 2022-12-23
  • 2021-10-02
  • 2021-11-30
  • 2021-07-27
猜你喜欢
  • 2021-09-20
  • 2022-12-23
  • 2021-07-05
  • 2021-12-05
  • 2021-09-20
相关资源
相似解决方案