views:

79

answers:

3

I know that .NET assembly is self-descriptive because of the metadata. Now suppose I have a black-box assembly which I know nothing about. Could I find out the types contained in it and use their methods and pass arguments? How? Sampe code snippets will be deeply appreciated.

[New Edit1]

I am not working at design time. I am trying to figure out how many arguments a type's method needs and what type these arguments are, so I can call the method at runtime using reflection.

[New Edit2]

I came up with the following code snippets. It construct an object from a black-box assembly. But it looks rather ugly, any better idea?

        foreach (ConstructorInfo ci in cis)
        {
            Console.WriteLine("{0}:{1}", ci.MemberType, ci.Name);
            Console.WriteLine("ReflectedType:{0}", ci.ReflectedType);
            ParameterInfo[] parameters = ci.GetParameters();
            Object[] arguments = new Object[parameters.Length];
            Console.WriteLine(parameters.Length);
            for (int i = 0; i < parameters.Length;i++ )
            {
                ParameterInfo para = parameters[i];
                if (para.ParameterType == typeof(Int32))
                {
                    Console.WriteLine("please input a Int32");
                    String input = Console.ReadLine();
                    Int32 para_int32 = Int32.Parse(input);
                    arguments[i] = para_int32;
                }

                if (para.ParameterType == typeof(String))
                {
                    Console.WriteLine("please input a String");
                    String para_String = Console.ReadLine();
                    arguments[i] = para_String;
                }

                //Add all the guesses...
            }
            Object o = ci.Invoke(arguments);

Many thanks.

+4  A: 

I'd suggest you take a look at the topics on Reflection, which would let you explore the meta data at runtime. Of course, if you're only interested in design-time, the IDE will let you explore the associated namespaces.

Rowland Shaw
+1  A: 

Assuming you are working at design-time, you should probably take a look at Reflector

http://reflector.red-gate.com/download.aspx?TreatAsUpdate=1

It allows you to browse an assembly's classes/methods/enums etc

Adam Pope
Thanks Adam. But I am not working at design time.
smwikipedia
A: 

Well, if you need the data at run-time, then you better be good at Reflection

I suggest you to read this page at least.

Example:

void doSomething(object obj)
{
    Type type = obj.GetType();
    foreach(MemberInfo mi in type.GetMembers())
    {
        //print the data or work on it.
    }
}
Nayan
This might be needed too! :)Link-> http://www.vcskicks.com/new-instance.php
Nayan