zoukankan      html  css  js  c++  java
  • 泛型约束和利用反射修改对象属性的值

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

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

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

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

    错误 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
  • 相关阅读:
    element-ui 和ivew-ui的table导出export纯前端(可用)
    webstrom 2019 注册码(可用 2019年10月14日08:59:18)
    intellji IDEA 2019版激活码(亲测可用 2019年10月14日08:53:54)
    java开发相关工具安装包分享
    js有关字符串拼接问题
    js增删class的方法
    有关定位问题
    关于网页元素居中常见的两种方法
    有关css编写文字动态下划线
    js获取时间及转化
  • 原文地址:https://www.cnblogs.com/scien626/p/4492749.html
Copyright © 2011-2022 走看看