代码之家  ›  专栏  ›  技术社区  ›  Rashedul.Rubel

在反射的帮助下使用泛型类访问具体类的属性

  •  -1
  • Rashedul.Rubel  · 技术社区  · 7 年前

    我可以使用接口实现和依赖注入知识做同样的事情,但我只想知道在这种情况下泛型的用法。

    假设我有几个类包含相同数量的相同类型的属性,并且在某些情况下它也包含相同签名的相同方法。例如,在这里有一个名为“老虎”的类的主操作程序。

    在上面的例子中,我如何使用泛型来减少代码,这样我就可以只传递所需的类作为参数来访问基于特定类的方法和get/set属性?

    注意:我可以用接口来做,但我不想。

    2 回复  |  直到 7 年前
        1
  •  0
  •   Kalyan Mondal    7 年前

    是的,反射是一种选择,但不建议这样做,因为它会占用大量内存。

    class MainApp
    {
        static void Main()
        {
            Cat cat = new Cat(4, "Black", true, "White");
    
            Tiger tiger = new Tiger(4, "Black", true, "Yellow");
    
            Cow cow = new Cow(4, "Black", true, "Black");
        }
    }
    
    public class Animal
    {
        public int Legs { get; set; }
    
        public string EyeColour { get; set; }
    
        public bool Tail { get; set; }
    
        public string SkinColour { get; set; }
    
        public Animal(int legs, string eyeColour, bool tail, string skinColour)
        {
            this.Legs = legs;
            this.EyeColour = eyeColour;
            this.Tail = tail;
            this.SkinColour = skinColour;
        }
    }
    
    public class Cat : Animal
    {
        public Cat(int legs, string eyeColour, bool tail, string skinColour) 
            : base(legs, eyeColour, tail, skinColour)
        {
        }
    
        public int MyPropertyCat { get; set; }
    }
    
    public class Tiger : Animal
    {
        public Tiger(int legs, string eyeColour, bool tail, string skinColour) 
            : base(legs, eyeColour, tail, skinColour)
        {
        }
    
        public int MyPropertyForTiger { get; set; }
    }
    
    public class Cow : Animal
    {
        public Cow(int legs, string eyeColour, bool tail, string skinColour)
            : base(legs, eyeColour, tail, skinColour)
        {
        }
    
        public int MyPropertyForCow { get; set; }
    }
    

    }

        2
  •  -1
  •   Grax32    7 年前

    在这种情况下,泛型并不适合。你要找的是duck类型,在C中最接近的就是使用dynamic关键字。

    public void FillAddress(string type)
    {
        if (_addressDetails == null) throw new Exception($"{nameof(_addressDetails)} must not be null.");
    
        dynamic details = _addressDetails;
        dynamic addressSource;
    
        if (type == "Manager")
        {
            addressSource = _manager;
        }
        else if (type == "TeamLead")
        {
            addressSource = _teamLead;
        }
        else if (type == "Employee")
        {
            addressSource = _employee;
        }
        else
        {
            throw new ArgumentException("Unrecognized type", nameof(type));
        }
    
        details.AddressLine1 = addressSource.AddressLine1;
        details.AddressLine2 = addressSource.AddressLine2;
        details.AddressLine3 = addressSource.AddressLine3;
    }
    

    )我不建议这样做。我在另一篇文章中评论说,你的朋友应该尝试使用分部类将接口应用于具有公共属性的类型。)