LoginSignup
2
3

More than 5 years have passed since last update.

明示的に実装されたインターフェースのメンバーはリフレクションからどう見えるか

Posted at

ググっても直球の答えが出てこなかったのでついカッとなって書いた。今は反省している。

namespace TypeTest {
    namespace Impl {
        class Program {
            static void Main(string[] args)
            {
                DumpMember<ImplicitTest>();
                DumpMember<ExplicitTest>();
                Console.ReadKey();
            }

            private static void DumpMember<T>()
            {
                Console.WriteLine($"== {typeof(T).Name} ==");
                foreach (var p in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) {
                    var accessibility = p.GetMethod.IsPublic ? "+"
                        : p.GetMethod.IsPrivate ? "-"
                        : p.GetMethod.IsAssembly ? "~"
                        : p.GetMethod.IsAbstract ? "/"
                        : "#";
                    Console.WriteLine($"{accessibility} {p.Name} : {p.PropertyType}");
                }
            }
        }

        public interface ITest {
            string Member { get; set; }
        }

        public class ExplicitTest : ITest {
            protected string MemberImpl { get; private set; } = "Explicit";
            string ITest.Member
            {
                get { return MemberImpl; }
                set { MemberImpl = value; }
            }

            public override string ToString()
            {
                return MemberImpl;
            }
        }

        public class ImplicitTest : ITest {
            public string Member { get; set; } = "Implicit";

            public override string ToString()
            {
                return Member;
            }
        }
    }
}

結果

== ImplicitTest ==
+ Member : System.String
== ExplicitTest ==
# MemberImpl : System.String
- TypeTest.Impl.ITest.Member : System.String
2
3
1

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
2
3