在循环中创建类的实例 [英] Create instance of classes in loop

查看:76
本文介绍了在循环中创建类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些包含一些具有相同行为的类的文件夹(它们包含一个获取int参数的Run函数,并且所有类都继承自同一个类)。

我需要在这些实例中创建循环实例类和使用参数执行它们的函数。

这就是我开始的 -

I have folder that contains some classes with the same behavior (they contain one Run function that get int param and all inherit from the same class).
I need to create in loop instance from these classes and execute their function with the parameter.
That is what I started-

f = GetTypesInNamespace(Assembly.GetExecutingAssembly(), "ConsoleApplication3.JJJ");
A[] a = new A[f.Count()];

for (int i = 0; i < a.Count(); a[i]=new A(), i++);
    for (int i = 0; i < a.Count(); i++)
        {
            // (a[i] as f[i].GetType()).Run(0);
        }





我不知道怎么继续,如果它好的话......



I don’t know how to continue, and if it's good at all…

推荐答案

否,如果您创建A类的新实例,则无法将其强制转换为派生类型:这不起作用。您所能做的就是将派生类型转换为继承链中较低的类型,例如它的基类型:

No, if you create a new instance of class A, then you can't cast it to a derived type: that doesn't work. All you can do is cast a derived type to a type lower in teh inheritance chain, such as it's base type:
public class A { }
public class AA : A { }
public class AB : A { }
public class AAA : AA { }
public class ABA : AB { }



您可以投射一个实例AA或AB到A,或者您可以将AAA的实例转换为A或AA,将ABA的实例转换为A或AB,但是您不能将A的实例转发给任何其他实例,或者转发给AAA或AB !



如果要为派生类调用Run方法,则需要显式创建派生类的实例,而不是创建instanc基类的e,并尝试神奇地获取派生类的实例。


You can cast an instance of AA or AB to A, or you can cast an instance of AAA to A or AA, and an instance of ABA to A or AB, but you can't cast an instance of A to any of the others, or of AAA to AB!

If you want to call the Run method for a derived class, then you need to create an instance of the derived class explicitly, not create an instance of the base class and try to "magically get" an instance of the derived class from that.


如果你的类在另一个程序集中,你可以使用反射:

(我创建了另一个包含类的库,并使用了对该库的反射。)



You can use reflection if your classes are in an another assembly as here:
(I have created another library that contains classes, and used reflection over that library.)

static void Main(string[] args)
{
    try
    {
        Assembly l = Assembly.LoadFile(@"d:\tmp\Test_ReflectionSampleLib.dll");
        var types = l.GetExportedTypes().ToList();
        var btype = types.First(t => t.Name == "Base");
        var dtypes = types.Where(t => t.BaseType == btype);
        int i = 0;
        foreach (var d in dtypes)
        {
            ConstructorInfo ci = d.GetConstructor(Type.EmptyTypes);
            MethodInfo mi = d.GetMethod("Foo");

            mi.Invoke(ci.Invoke(null), new object[] { i++ });
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
    }
}


这篇关于在循环中创建类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆