Skip to content

Instantly share code, notes, and snippets.

@sonoichi60
Created August 12, 2018 03:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sonoichi60/bc944aadd204dd1b45a5cd61d0645285 to your computer and use it in GitHub Desktop.
Save sonoichi60/bc944aadd204dd1b45a5cd61d0645285 to your computer and use it in GitHub Desktop.
example PropertyInfo
// メンバプロパティの取得
var property = type.GetProperty("Property", BindingFlags.NonPublic | BindingFlags.Instance);
// メンバインデクサの取得
var returnType = typeof(int);
var paramTypes = new Type[] { typeof(int), typeof(int) };
var indexer = type.GetProperty("Indexer", returnType, paramTypes);
// メンバプロパティの全取得
var properties = typeof(TestClass).GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
var propertyType = property.PropertyType; // プロパティタイプ
var accessors = property.GetAccessors(true); // プロパティのアクセサ(get/set)を全取得
var getter = property.GetGetMethod(true); // getter取得
var setter = property.GetSetMethod(true); // setter取得
var parameters = property.GetIndexParameters(); // インデクサのパラメタ一覧取得
// publicか(set/set のいずれかがpublic)
var isPublic = accessors.Any(accessor => accessor.IsPublic);
// protectedか(publicでなく、set/set のいずれかがprotected)
var isFamily = !isPublic && accessors.Any(accessor => accessor.IsFamily);
var instance = new TestClass();
if (getter != null)
{
// 値のゲット(インデクサでない場合)
var value = getter.Invoke(instance, new object[0]);
}
if (setter != null)
{
// 値のセット(int 型のプロパティの場合)
setter.Invoke(instance, new object[] { 1 });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment