Using a .NET Object

Creating a .NET Object

You often need to create objects when working with .NET classes. An object is an instance of a particular class. Methods are functions that operate exclusively on objects of a class. Data types package together objects and methods so that the methods operate on objects of their own type. For more information about objects, see Using Objects in the Programming Fundamentals documentation.

You construct .NET objects in the MATLAB workspace by calling the class constructor, which has the same name as the class. The syntax to create a .NET object classObj is:

classObj = namespace.ClassName(varargin)

where varargin is the list of constructor arguments to create an instance of the class specified by ClassName in the given namespace. For an example, see Select a Constructor in Getting Started with .NET.

Using netdoc.NetSample

MATLAB includes a collection of sample C# classes in an assembly called NetSample. The examples in this topic use these classes to illustrate working with .NET objects in MATLAB.

Reference
NetSample

Namespace

netdoc

Assembly

NetSample (in NetSample.dll)

Source files

NetSample.sln and .cs files

Source folder

matlabroot\extern\examples\net\NetSample

NetSample contains the following classes.

Class Name
Purpose

SampleProperties

Sample declarations to show how MATLAB handles .NET properties

SampleFields

Sample declarations to show how MATLAB handles .NET fields

SampleMethods

Sample declarations to show how MATLAB handles .NET methods

SampleMethodSignature

Sample declarations to show how MATLAB displays .NET method signatures

Building a .NET Application for MATLAB Examples

To use the NetSample classes, build an application using a C# development tool, like Microsoft Visual Studio. The following are basic steps to do this; consult your development tool documentation for specific instructions.

  1. Copy the contents of the matlabroot\extern\examples\net\NetSample folder to a working folder, such as C:\work.

  2. From your development tool, open NetSample as a project and build it as a DLL.

  3. The name of this assembly is NetSample. Note the full path to the NetSample.dll file. Since it is a private assembly, you must use the full path to load it in MATLAB.

  4. After you load the assembly, if you modify and rebuild it, you must restart MATLAB to access the new assembly. You cannot unload an assembly in MATLAB.

.NET Properties in the MATLAB Workspace

The following topics describe using .NET properties in MATLAB.

  • Using Properties in MATLAB

  • C# Property Access Modifiers

  • .NET Fields in the MATLAB Workspace

  • Using .NET Properties Example

  • Using .NET Fields Example

  • Limitations to Support of .NET Properties

Using Properties in MATLAB

Use the properties function to view property names. For an example using the System.DateTime structure, see View Properties. To get and set the value of a class property, use the standard MATLAB dot notation:

x = myObject.MyProp; %get
myObject.MyProp = y; %set
C# Property Access Modifiers

MATLAB maps C# keywords to MATLAB property attributes, as shown in the following table. For more information about MATLAB properties, see Property Attributes in the MATLAB Object-Oriented Programming documentation.

C# Keyword
MATLAB Attribute

public, static
Access = public

protected, private, internal
Not visible to MATLAB

get, set
Access = public

Get
GetAccess = public, SetAccess = private

Set
SetAccess = public, GetAccess = private

.NET Fields in the MATLAB Workspace

MATLAB represents public fields as properties. For example, the System.String class has one field, Empty. To view it, type:

str = System.String('my new string');
properties(str)

MATLAB displays:

Properties for class System.String:
    Length
    Empty

MATLAB maps C# keywords to MATLAB field attributes, as shown in the following table.

C# Keyword
MATLAB Mapping

public
Supported

protected, private, internal, protected internal
Not visible to MATLAB

Using .NET Properties Example

The SampleProperties class defines the following public properties:

  • stringProp

  • doubleProp

  • readOnlyProp

  • writeOnlyProp

SampleProperties Class. 

using System;
namespace netdoc
{
    class SampleProperties
    {
        // string property
        private static string stringField = "The MathWorks";
        public static string stringProp
        {
            get { return stringField; }
            set { stringField = value; }
        }

        // read/write property
        private double doubleField = 8.9;
        public double doubleProp
        {
            get { return doubleField; }
            set { doubleField = value; }
        }

        // read-only property
        private double readField = 0;
        public double readOnlyProp
        {
            get { return readField; }
        }

        // write-only property
        private double writeField = 0;
        public double writeOnlyProp
        {
            set { writeField = value; }
        }
    }
}

Create Object.  Load the assembly and create object obj:

sampleInfo = NET.addAssembly('c:\work\NetSample.dll');
obj = netdoc.SampleProperties

MATLAB displays the object as follows:

obj = 
  netdoc.SampleProperties handle
  Package: netdoc

  Properties:
      stringProp: [1x1 System.String]
      doubleProp: 8.9000
    readOnlyProp: 0

  Methods, Events, Superclasses

MATLAB displays the stringProp, doubleProp, and readOnlyProp properties, but not the writeOnlyProp property. MATLAB also does not display properties defined with the private keyword, such as stringField and doubleField.

View Property Values.  To view the value of stringProp, type:

obj.stringProp

MATLAB displays:

ans = 
The MathWorks

Use Property Values.  To use the properties, type:

db1 = obj.doubleProp
db2 = obj.readOnlyProp

MATLAB displays:

db1 =
    8.9000
db2 =
     0

Modify Property Values.  To modify the properties, type:

obj.doubleProp = 5;
obj.writeOnlyProp = 6;
obj

MATLAB displays (in part):

obj = 

  Properties:
      stringProp: [1x1 System.String]
      doubleProp: 5
    readOnlyProp: 0

To modify the static property stringProp, type:

NET.setStaticProperty('netdoc.SampleProperties.stringProp', ...
    'This is a static property');
newVal = obj.stringProp

MATLAB displays:

newVal = 
This is a static property
Using .NET Fields Example

The SampleFields class defines the following fields:

  • publicField

  • protectedField

SampleFields Class. 

using System;
namespace netdoc
{
    class SampleFields
    {
        public Int32 publicField;
        protected string protectedField;
    }
}

Create Object.  Load the assembly and create object obj:

NET.addAssembly('c:\work\NetSample.dll')
obj = netdoc.SampleFields;

Modify Field Values.  To set the value of the field publicField, type:

myValue = 3;
obj.publicField = myValue

MATLAB displays:

obj = 
  netdoc.SampleFields handle
  Package: netdoc

  Properties:
    publicField: 3

  Methods, Events, Superclasses

The publicField property is of type Int32. When you set the value to myValue, which is of MATLAB type double, MATLAB automatically converts the value to the proper type, as described in Passing Data to a .NET Object. Type:

class(myValue)
class(obj.publicField)

MATLAB displays:

ans =
double
ans =
int32
Limitations to Support of .NET Properties

You cannot pass a cell array to a property, or view protected properties in MATLAB.

.NET Methods in the MATLAB Workspace

The following topics describe using .NET methods in MATLAB.

  • Getting Method Information

  • Calling Nonstatic Methods

  • Calling Static Methods

  • Calling Generic Methods

  • Calling .NET Properties That Take an Argument

  • C# Method Access Modifiers

  • Method Signatures

  • Operator Overloading

  • Using .NET Methods Example

  • Method Signature Example

  • Limitations to Support of .NET Methods

Getting Method Information

Use the following MATLAB functions to view the methods of a class. You can use these functions without creating an instance of the class. These functions do not list generic methods; use your product documentation to get information on generic methods.

  • methods — View method names

  • methods with '-full' option — View method names with argument list

  • methodsview — Graphical representation of method list

You might find the methodsview window easier to use as a reference guide because you do not need to scroll through the Command Window to find information. For example, open a methodsview window for the System.String class:

methodsview('System.String')

The following topics refer to method signatures in this display.

Calling Nonstatic Methods

You can use either function notation or dot notation syntax for calling standard (nonstatic) methods of a class. These functions operate on an object. For example, Contains is a method of the System.String class. Its method signature is:

logical scalar RetVal Contains(System.String this, 
  System.String value)

To use this method, first create an object, str1:

str1 = System.String('The colors are red and white');

To call Contains using function notation, type:

flag = Contains(str1,'red');

To call Contains using dot notation, type:

flag = str1.Contains('red');

In either case, the value of flag is 1 (true).

Calling Static Methods

A static method does not operate on a single object. You must use the fully qualified name when you call a static method. For example, Concat is a static method of the System.String class. One of its method signatures is:

Static System.String RetVal Concat(System.String str0, 
  System.String str1, System.String str2)

Given the following value for object str2:

str2 = System.String(' and blue');

you must use the function notation to concatenate str1 and str2:

newstr = System.String.Concat(str1,str2)

MATLAB displays:

newstr = 
The colors are red and white and blue
Calling Generic Methods

Use the NET.invokeGenericMethod function to call a generic method.

Calling .NET Properties That Take an Argument

MATLAB represents a property that takes an argument as a method. For example, the System.String class has two properties, Chars and Length. The Chars property gets the character at a specified character position in the System.String object:

str = System.String('my new string');
methods(str)

MATLAB displays (in part):

Methods for class System.String:

Chars             Insert            ToCharArray       findobj 
Clone             IsNormalized      ToLower           findprop
CompareTo         LastIndexOf       ToLowerInvariant  ge      
Contains          LastIndexOfAny    ToString          gt      
...

To see the first character, type:

str.Chars(0)

MATLAB displays:

ans =
m
C# Method Access Modifiers

MATLAB maps C# keywords to MATLAB method access attributes, as shown in the following table.

C# Keyword
MATLAB Attribute

ref
RHS, LHS

out
LHS

params
Array of particular type

protected, private, internal, protected internal
Not visible to MATLAB

VB.NET Keyword
MATLAB Attribute

ByRef
LHS, RHS

ByVal
RHS

Optional
Mandatory

Method Signatures

MATLAB uses the following rules to populate method signatures.

  • obj is the output from the constructor.

  • this is the object argument.

  • RetVal is the return type of a method.

  • All other arguments use the .NET metadata.

MATLAB uses the following rules to select a method signature.

  • Number of inputs

  • Input type

  • Number of outputs

Operator Overloading

MATLAB supports overloaded operators, such as the C# operator symbols + and *, as shown in the following table. MATLAB implements all other overloaded operators, such as % and +=, by their static method names, op_Modulus and op_AdditionAssignment. For a complete list of operator symbols and the corresponding operator names, see http://msdn.microsoft.com/en-us/library/2sk3x8a7(VS.71).aspx on the Microsoft Developer Network Web site.

C++ operator symbol
.NET operator
MATLAB methods

+ (binary)
op_Addition
plus, +

- (binary)
op_Subtraction
minus, -

* (binary)
op_Multiply
mtimes, *

/
op_Division
mrdivide, /

&&
op_LogicalAnd
and, &

||
op_LogicalOr
or, |

==
op_Equality
eq, ==

>
op_GreaterThan
gt, >

<
op_LessThan
lt, <

!=
op_Inequality
ne, ~=

>=
op_GreaterThanOrEqual
ge, >=

<=
op_LessThanOrEqual
le, <=

- (unary)
op_UnaryNegation
uminus, -a

+ (unary)
op_UnaryPlus
uplus, +a

Using .NET Methods Example

The SampleMethods class defines the following methods:

  • addTwoDoubles

  • multiplyInts

  • refOutTest

  • paramsTest

SampleMethods Class. 

using System;
namespace netdoc
{
    class SampleMethods
    {
        //static method
        public static double addTwoDoubles(double num1, double num2)
        {
            return num1 + num2;
        }
        
        //standard method
        public Int32 multiplyInts(Int32 num1, Int32 num2)
        {
            return num1 * num2;
        }

        //test ref and out keyword
        public void refOutTest(ref double db1, out double db2)
        {
            db1 = db1 * 2;
            db2 = db1;
        }

        //test params keyword
        public int paramsTest(params int[] num)
        {
            int total = 0;
            foreach (int i in num)
            {
                total = total + i;
            }
            return total;
        }

    }
}

Calling Methods Examples.  If you have not already loaded the NetSample assembly, type:

NET.addAssembly('c:\work\NetSample.dll')

Call the static method addTwoDoubles:

db1 = netdoc.SampleMethods.addTwoDoubles(2, 3)

MATLAB displays:

db1 =
     5

To call the nonstatic method multiplyInts, you must first create an object:

obj = netdoc.SampleMethods;
db2 = obj.multiplyInts(2, 3)

MATLAB displays:

db2 =
           6

To capture the output from a method using the ref and out keywords, use the refOutTest method. Its function signature is:

[double scalar db1, double scalar db2] refOutTest
  (netdoc.SampleMethods this, double scalar db1)

Type:

[db4 db3] = obj.refOutTest(6)

MATLAB displays:

db4 =
    12
db3 =
    12

To call a method using a params keyword, use the paramsTest method. The function signature is:

int32 scalar RetVal paramsTest(netdoc.SampleMethods this, 
  System.Int32[] num)

Type:

mat  = [1, 2, 3, 4, 5, 6];
mat = NET.convertArray(int32(mat));
db5 = obj.paramsTest(mat)

MATLAB displays:

db5 =
          21
Method Signature Example

The SampleMethodSignature class defines the following three constructors:

  • netdoc.SampleMethodSignature obj SampleMethodSignature

  • netdoc.SampleMethodSignature obj SampleMethodSignature (double scalar d)

  • netdoc.SampleMethodSignature obj SampleMethodSignature (System.String s)

SampleMethodSignature Class. 

using System;
namespace netdoc
{
    public class SampleMethodSignature
    {
        public SampleMethodSignature ()
        {}
        
        public SampleMethodSignature (double d)
        { myDoubleField = d; }
        
        public SampleMethodSignature (string s)
        { myStringField = s; }

        public int myMethod(string strIn, ref double dbRef, 
					out double dbOut)
        {
            dbRef += dbRef;
            dbOut = 65;
            return 42;
        }

        private Double myDoubleField = 5.5;
        private String myStringField = "hello";
    }
}

Display Function Signature Example.  If you have not already loaded the NetSample assembly, type:

NET.addAssembly('c:\work\NetSample.dll')

Create a SampleMethodSignature object obj:

obj = netdoc.SampleMethodSignature;

To see the method signatures, type:

methods(obj, '-full')

Look for the following signatures in the MATLAB output:

netdoc.SampleMethodSignature obj SampleMethodSignature
netdoc.SampleMethodSignature obj SampleMethodSignature(double scalar d)
netdoc.SampleMethodSignature obj SampleMethodSignature(System.String s)

For more information about argument types, see Handling Data Returned from a .NET Object.

Limitations to Support of .NET Methods

You cannot pass a cell array to a .NET method. The methods and methodsview functions do not list generic methods.

.NET Events in the MATLAB Workspace

Use the addlistener function to handle events from .NET objects.

For example, you can monitor changes to files using the System.IO.FileSystemWatcher class in the System assembly. Create the following event handler, eventhandlerChanged.m:

function eventhandlerChanged(source,arg)
  disp('TXT file changed')
end

Create a FileSystemWatcher object fileObj and watch the Changed event for files with a .txt extension in the folder C:\work\temp.

fileObj = System.IO.FileSystemWatcher('c:\work\temp');
fileObj.Filter = '*.txt';
fileObj.EnableRaisingEvents = true;
addlistener(fileObj, 'Changed', @eventhandlerChanged);

If you modify and save a .txt file in the C:\work\temp folder, MATLAB displays:

TXT file changed

The FileSystemWatcher documentation says that a simple file operation can raise multiple events.

To turn off the event handler, type:

fileObj.EnableRaisingEvents = false;
MATLAB Supports Standard Signature of an Event Handler Delegate

An event handler in C# is a delegate with the following signature:

public delegate void MyEventHandler(object sender, MyEventArgs e)

The argument sender specifies the object that fired the event. The argument e holds data that can be used in the event handler. The class MyEventArgs is derived from the .NET Framework class EventArgs. MATLAB only handles events with this standard signature.

.NET Delegates in the MATLAB Workspace

In the .NET Framework, a delegate is a type that defines a method signature. It lets you pass a function as a parameter. The use of delegates enables .NET applications to make calls into MATLAB callback functions or class instance methods. For the rules MATLAB uses to define the signature of a callback function or class method, see Method Signatures in Using a .NET Object. For a complete description of delegates and when to use them, consult an outside resource such as the Microsoft Developer Network.

There are three steps to using delegates:

  • Declaration — Your .NET application contains the declaration. You cannot declare a delegate in the MATLAB language.

  • Instantiation — In MATLAB, create an instance of the delegate and associate it with a specific MATLAB function or .NET object method.

  • Invocation — Call the function, using the delegate name in place of the function name, with specified input and output arguments.

Calling a Delegate in MATLAB

This example shows you how to use a delegate in MATLAB. It creates a delegate using a MATLAB function (char). For another example, see Creating a Delegate from a .NET Object Method.

This example consists of the following tasks:

  1. Declare a Delegate in a C# Assembly

  2. Load Assembly Containing Delegate into MATLAB

  3. Select a MATLAB Function

  4. Create an Instance of the Delegate in MATLAB

  5. Invoke the Delegate Instance in MATLAB

Declare a Delegate in a C# Assembly.  The following C# statements declare a delegate, delInteger, which encapsulates any method that takes an integer input and returns a string. You need to build the assembly NetDocDelegate in order to run these examples. For information, see Building a .NET Application for MATLAB Examples.

using System;
namespace NetDocDelegate
{
    public delegate string delInteger(int x);
}

Load Assembly Containing Delegate into MATLAB.  If the NetDocDelegate assembly is in your c:\work folder, load the file with the command:

NET.addAssembly('c:\work\NetDocDelegate.dll');

Select a MATLAB Function.  The MATLAB char function, which converts a nonnegative integer into a character array (string), has a signature that matches the delInteger delegate. For example, the following command displays the ! character:

char(33)

Create an Instance of the Delegate in MATLAB.  To create an instance of the delInteger delegate, pass the function handle of the char function:

myFunction = NetDocDelegate.delInteger(@char);

Invoke the Delegate Instance in MATLAB.  Use myFunction like you would char. For example, the following command displays the ! character:

myFunction(33)
Creating a Delegate from a .NET Object Method

The following C# class defines the methods AddEggs and AddFlour, which have signatures matching the delInteger delegate:

using System;

namespace Recipe
{
    public class MyClass
    {
        public string AddEggs(double n)
        {
            return "Add " + n + " eggs";
        }

        public string AddFlour(double n)
        {
            return "Add " + n + " cups flour";
        }
    }
}

Create a delegate myFunc using AddEggs as the callback:

NET.addAssembly('c:\work\NetDocDelegate.dll');
NET.addAssembly('c:\work\Recipe.dll');
obj = Recipe.MyClass;
myFunc = NetDocDelegate.delInteger(@obj.AddEggs);
myFunc(2)

MATLAB displays:

ans = 
Add 2 eggs
Creating a Delegate Instance Bound to a .NET Method

For a C# delegate defined as:

namespace MyNamespace
{
  public delegate void MyDelegate();
}

MATLAB creates the following constructor signature:

MyNamespace.MyDelegate obj MyDelegate (target, string methodName)

where target is one of the following:

  • an instance of the invocation target object when binding to the instance method.

  • a string with fully qualified .NET class name when binding to a static method.

and methodName is a string specifying the callback method name.

Example — Create a Delegate Instance Associated with a .NET Object Instance Method.  For the following C# delegate and class definition:

namespace MyNamespace
{
  public delegate void MyDelegate();

  public class MyClass
  {
    public void MyMethod(){}
  }
}

To instantiate the delegate in MATLAB, type:

targetObj = MyNamespace.MyClass();
delegateObj = MyNamespace.MyDelegate(targetObj, 'MyMethod');

Example — Create a Delegate Instance Associated with a Static .NET Method.  For the following C# delegate and class definition:

namespace MyNamespace
{
  public delegate void MyDelegate();

  public class MyClass
  {
    public static void MyStaticMethod(){}
  }
}

To instantiate the delegate in MATLAB, type:

delegateObj=MyNamespace.MyDelegate('MyNamespace.MyClass','MyStaticMethod');
Combining and Removing Delegates

MATLAB provides the instance method Combine, that lets you combine a series of delegates into a single delegate.

For example, create the following MATLAB functions to use with the NetDocDelegate.delInteger delegate:

function out = action1(n)
out = 'Add flour';
disp(out);
end
function out = action2(n)
out = 'Add eggs';
disp(out);
end

Create delegates step1 and step2:

step1 = NetDocDelegate.delInteger(@action1);
step2 = NetDocDelegate.delInteger(@action2);

To combine into a new delegate, mixItems, type:

mixItems = step1.Combine(step2);

Or, type:

mixItems = step1.Combine(@action2);

Invoke mixItems:

result = mixItems(1);

In this case, the function action2 follows action1:

Add flour
Add eggs

The value of result is the output from the final delegate (step2).

result = 
Add eggs

You can also use the System.Delegate class static methods, Combine, Remove and RemoveAll.

To remove a step1 from mixItems, type:

step3 = mixItems.Remove(step1);

To remove all from the original mixItems, type:

mixItems = step1.Combine(step2);
mixItems.RemoveAll;
Limitations to Support of .NET Delegates

MATLAB does not support:

  • Asynchronous delegate callback invocation.

  • Associating a delegate instance with a generic .NET method.

What Classes Are in a .NET Assembly?

The product documentation for your assembly contains information about its classes. However, you can use the NET.addAssembly command to read basic information about an assembly. For example, for the private assembly netdoc.NetSample, type:

sampleInfo = NET.addAssembly('c:\work\NetSample.dll');

Assembly netdoc.NetSample has five classes. To view the names, type:

sampleInfo.Classes

MATLAB displays:

ans = 
    'netdoc.SampleMethodSignature'
    'netdoc.SampleMethods'
    'netdoc.NetSample'
    'netdoc.SampleFields'
    'netdoc.SampleProperties'

For a description of the Sample* classes, see Using netdoc.NetSample. The NetSample class is empty; it is used to create the assembly name.

If your assembly has hundreds of entries, you can consult the product documentation, or open a window to an online document, such as the System namespace reference page on the Microsoft Developer Network. For information about using this documentation, see To Learn More About the .NET Framework. For example, to find the number of classes nclasses in mscorlib, type:

asm = NET.addAssembly('mscorlib');
[nclasses,x] = size(asm.Classes);
Using the delete Function on a .NET Object

Objects created from .NET classes appear in MATLAB as reference types, or handle objects. Calling the delete function on a .NET handle releases all references to that .NET object from MATLAB, but does not invoke any .NET finalizers. The .NET Framework manages garbage collection.

posted @ 2011-11-21 23:33  甲今文  阅读(895)  评论(0编辑  收藏  举报