Use .NET Nested Classes and Enumerations
Instantiate Nested Class Through Reflection
In MATLAB®, you cannot directly instantiate a nested class or enumeration, but
here is how to do it through reflection using
System.Reflection.
This MyClassLibrary.cs file defines
InnerClass nested in OuterClass.
namespace MyClassLibrary {
public class OuterClass {
public class InnerClass {
public String strmethod(String x) {
return "from InnerClass " + x;
}
}
}
}To build and load the MyClassLibrary assembly, see Build and Load .NET Assembly for MATLAB.
Display the classes.
a.Classes
ans =
'MyClassLibrary.OuterClass'
'MyClassLibrary.OuterClass+InnerClass'
The + character in class
MyClassLibrary.OuterClass+InnerClass indicates that
InnerClass is nested in OuterClass. You
cannot directly instantiate a nested class or enumeration from a .NET assembly. To
call strmethod, which is a member of
Innerclass, create a
MyClassLibrary.OuterClass+InnerClass object using the
AssemblyHandle.GetType method in
System.Reflection.
t = a.AssemblyHandle.GetType("MyClassLibrary.OuterClass+InnerClass"); sa = System.Activator.CreateInstance(t); strmethod(sa,"hello")
ans = from InnerClass hello
Create Nested Constructors with or without Parameters
Suppose that you have this MyClassLibrary.cs file. To build and
load the MyClassLibrary assembly, see Build and Load .NET Assembly for MATLAB. The source code is:
namespace MyClassLibrary {
public class OuterClass {
public class Nested {
public Nested() {};
public Nested(int i, double d) {};
}
public enum Direction { North=0, East=90, South=180, West=270};
}
}Create an object to represent the East enumeration.
t.GetEnumValues.Get(1)
t = asm.AssemblyHandle.GetType("MyClassLibrary.OuterClass+Direction");ans = East
The Nested class is overloaded. Create an instance of the
Nested class using the constructor without parameters.
t = asm.AssemblyHandle.GetType("MyClassLibrary.OuterClass+Nested");
obj = System.Activator.CreateInstance(t);Create an instance of the Nested class using the constructor
with parameters.
t = asm.AssemblyHandle.GetType("MyClassLibrary.OuterClass+Nested"); params = NET.createArray("System.Object",2); params(1) = 1; params(2) = 3.6; obj = System.Activator.CreateInstance(t,params,[]);