11
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[C#] GetMembers(), GetFields(), GetProperties(), GetMethods()の違い

Posted at

前書き

Type.GetProperties() を試してみた時に、他のGetMembers(), GetFields(), GetMethods() で取得できる値の違いがわからなかったので、試してみた。

コード

まず、Hogeクラスを用意。

    class Hoge
    {
        public int field1;
        public int[] field2;
        private int field3;

        public int property1 { get; set; }
        public int property2 { get; private set; }

        public void func1() { return; }
        public int func2() { return 0; }
        private void func3() { }
    }

そして、Hogeクラス内のMember, Field, Property, MethodのNameプロパティを表示する。

    class Program
    {
        static void Main(string[] args)
        {
            var type = new Hoge().GetType();

            var members = type.GetMembers();

            Console.WriteLine("[members]");
            foreach (var m in members)
            {
                Console.WriteLine(m.Name);
            }
            Console.WriteLine();

            var fields = type.GetFields();

            Console.WriteLine("[fields]");
            foreach (var f in fields)
            {
                Console.WriteLine(f.Name);
            }
            Console.WriteLine();

            var properties = type.GetProperties();

            Console.WriteLine("[properties]");
            foreach (var p in properties)
            {
                Console.WriteLine(p.Name);
            }
            Console.WriteLine();

            var methods = type.GetMethods();

            Console.WriteLine("[methods]");
            foreach (var m in methods)
            {
                Console.WriteLine(m.Name);
            }
            Console.WriteLine();

            Console.ReadLine();
        }
    }

結果

概ね予想通りに表示された。
publicは表示されるが、privateは表示されない。

[members]
get_property1
set_property1
get_property2
func1
func2
ToString
Equals
GetHashCode
GetType
.ctor
property1
property2
field1
field2

[fields]
field1
field2

[properties]
property1
property2

[methods]
get_property1
set_property1
get_property2
func1
func2
ToString
Equals
GetHashCode
GetType

まとめ

結果から、

  • GetMembers() : クラス内のメンバ
  • GetFields() : クラス内のフィールド
  • GetProperties() : クラス内のプロパティ
  • GetMethods() : クラス内のメソッド

が取得できる事がわかった。

11
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?