【问题标题】:extracting list from an object and using its methods从对象中提取列表并使用其方法
【发布时间】:2015-10-24 03:18:12
【问题描述】:

我试图获取一个函数列表,而获取列表的变量是一个对象。 我正在尝试为函数创建一个通用选项,无需为特定列表设置函数。

class Program
{
    static void Main(string[] args)
    {
        Car Ford = new Car();
        Car Toyota = new Car();
        Motorcycle Kawasaki = new Motorcycle();
        Bike Zebra = new Bike();
        List<Vehicle> Garage = new List<Vehicle>();
        Garage.Add(Ford);
        Garage.Add(Toyota);
        Garage.Add(Kawasaki);
        Garage.Add(Zebra);
        Class1 c1 = new Class1(Garage);
    }
 }
class Class1
{
    public Class1(object obj)
    {
       //cannot find the way to extract the list and its method 
    }

}

我可以在 obj 中看到列表,但我无法使用它(无法循环类并且不使用它们的公共方法。 我知道有一些使用反射的可能性,但我只能使用一个类而不是一个列表。 这里有什么帮助吗?

【问题讨论】:

  • 我不明白?只需将构造函数中的对象替换为 list 并将garage 作为参数传递?
  • 我不想写列表 因为我希望对象能够获取,并且我将使用反射来使用方法
  • 那么你说的是哪个对象?
  • class Class1 { public Class1(object obj) { //找不到提取列表的方法及其方法 } }
  • @YDG 你想实际做什么?这是错误的做法。

标签: c#


【解决方案1】:

您可以为此使用 Generic

class Program
{
    static void Main(string[] args)
    {
        Car Ford = new Car();
        Car Toyota = new Car();
        Motorcycle Kawasaki = new Motorcycle();
        Bike Zebra = new Bike();
        List<Vehicle> Garage = new List<Vehicle>();
        Garage.Add(Ford);
        Garage.Add(Toyota);
        Garage.Add(Kawasaki);
        Garage.Add(Zebra);
        Class1<Vehicle> c1 = new Class1<Vehicle>(Garage);
    }        
}

 class Bike : Vehicle
{
}

 class Car : Vehicle
{
}

 class Motorcycle : Vehicle
{
}

 class Vehicle
{
}

class Class1<T> 
{
    public Class1(List<T> obj)
    {
        foreach (var item in obj)
        {

        }            
    }
}

【讨论】:

  • foreach (var item in obj) { //这是运行方法 item.GetType().GetMethod(methodname).Invoke(item, null); }
  • 我不明白...你现在需要什么??
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-17
  • 2019-12-21
  • 2022-01-07
  • 2013-05-17
  • 2018-07-13
相关资源
最近更新 更多