zoukankan      html  css  js  c++  java
  • 不用继承接口,一样可以把一个没有继承接口的类来实例化接口

    public interface IName 
        {
            int Age { get; set; }
            string Name { get; set; }
        }
      
        public class Person 
        {
            public int Age{get;set;}
            public string Name { get; set; }
            public Person()
            { }
            public Person(string name,int age)
            {
                Name = name;
                Age = age;
            }
        }
      
        public class EmptyEntity : IName
        {
            public string Name { get; set; }
            public int Age { get; set; }
        }
      
        public class ClassToInterface
        {
            /// <summary>
            /// 
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <typeparam name="TResult">it implements the interface.</typeparam>
            /// <returns></returns>
            public static IName ConvertClassToInterface<T>(T obj)
            {
                IName entity=new EmptyEntity();
                PropertyInfo[] descProperties = typeof(IName).GetProperties();
                Type type = obj.GetType();
                foreach(PropertyInfo propertyInfo in descProperties)
                {
                    propertyInfo.SetValue(entity,type.GetProperty(propertyInfo.Name).GetValue(obj, null), null);
                }
                Console.WriteLine("Result:{0}={1}",entity.Name,entity.Age);
                return entity;
            }
      
        }
  • 相关阅读:
    C#中静态变量 静态类 静态成员
    C#类型转换
    ASP.NET页面跳转及传值方式
    ADO.NET
    C#方法的参数类型
    Oracle %TYPE 和 %ROWTYPE
    静态页面与动态页面
    相对路径和绝对路径
    45 个非常有用的 Oracle 查询语句(转)
    ASP.NET MVC 之表格分页
  • 原文地址:https://www.cnblogs.com/hongjiumu/p/2774729.html
Copyright © 2011-2022 走看看