3

I'm using C# for developing mobile applications(Monotouch, monodroid). I have a class by this definition:

public class TempIOAddOn : BaseIOAddOn 
{
    public TempIOAddOn ()
    {
    }
}

And I use this code to access an instance of class by its string name:

BaseIOAddOn tempIOAddOn;
            Type t= Type.GetType("TempIOAddOn" );
            tempIOAddOn  = (BaseIOAddOn)Activator.CreateInstance(t);

But after executation, t is null.

I tried below code also:

BaseIOAddOn tempIOAddOn;
            tempIOAddOn = (BaseIOAddOn )System.Reflection.Assembly.GetExecutingAssembly().CreateInstance("TempIOAddOn" );

But again I face with null. tempIOAddOn is null.

What is wrong with me?

4

2 回答 2

8

Your class is almost certainly included in a namespace. In this case you need to qualify the name of the type with its namespace:

Type t= Type.GetType("MyNamespace.TempIOAddOn");
于 2013-04-27T11:49:38.687 回答
5

Try using the Assembly Qualified Name instead. If it's running Xamarin, it might need to use the full qualified name. I've had the same limitations with Silverlight.

To quickly get the full name, just reference the type and output it:

Console.WriteLine(typeof(TempIOAddon).AssemblyQualifiedName);

EDIT: Here's the MSDN doc for Type.GetType(string) for Silverlight. Since Xamarin's mobile platform is more or less based off it, generally the docs can apply: http://msdn.microsoft.com/en-us/library/w3f99sx1%28v=vs.95%29.aspx

Note that likely if the type is in the currently executing assembly, you'll probably only need the full namespace.name

于 2013-04-27T11:47:54.347 回答