Per Erik Strandberg /cv /kurser /blog

ISFIELD in Matlab

Lets make a struct with the fields b and c, b has the subfields b1 and b2:

>> A = [];
>> A.b = [];
>> A.b.b1 = 'b1';
>> A.b.b2 = 'b2';
>> A.c = 3.14;
>> A

A = 

    b: [1x1 struct]
    c: 3.1400

>> A.b

ans = 

    b1: 'b1'
    b2: 'b2'


Now we might want to know is there is a field in A that is called b:

>> isfield(A,'b')

ans =

     1

GETMEMBERS in C#

We create a silly class Ring with an integer id and a string owner. Then we scan the object (or an instance of type Type with the value Ring.) (Type theType = przs.GetType()). We print the members on The Console.

using System;
using System.Reflection;

namespace hasMemberTest
{
  // Silly class to test on
  class Ring
  {
    public int Id;
    public string Owner;

    // ctor sets id and owner
    public Ring(int id, string BelongsTo)
    {
      this.Id = id;
      this.Owner = (string)BelongsTo.Clone();
    }

    // testprogram
    static void Main(string[] args)
    {
      // create the precious
      Ring przs = new Ring(1, "Sauron, who else? (A stinking hobbit?)");
      Console.WriteLine("Ctor'ed ring #{0} belonging to '{1}'.",
        przs.Id, przs.Owner);

      // get type and members
      Type theType = przs.GetType();
      MemberInfo[] mbrInfoArray = theType.GetMembers();

      // write all members
      Console.WriteLine("The '{0}' has the following members", theType);
      foreach (MemberInfo mbrInfo in mbrInfoArray)
      {
        Console.WriteLine("  - {0,32} is a {1,16}", mbrInfo, mbrInfo.MemberType);
      }
    }
  }
}


The output should be something like this:

Ctor'ed ring #1 belonging to 'Sauron, who else? (A stinking hobbit?)'.
The 'hasMemberTest.Ring' has the following members
  -            System.Type GetType() is a           Method
  -         System.String ToString() is a           Method
  -    Boolean Equals(System.Object) is a           Method
  -              Int32 GetHashCode() is a           Method
  - Void .ctor(Int32, System.String) is a      Constructor
  -                         Int32 Id is a            Field
  -              System.String Owner is a            Field



So, indeed, we can check if there is a field in a class - but I would not recommend it since there are better ways of doing it. (See Csharp Inheritance.)


This page belongs to the category Kategori Programmering.