次の 2 つのオプションがあります。
publicの代わりにプロパティを作成しprivateます。
reflectionプロパティにアクセスするために使用します。
(1) を使用することをお勧めします。
また、初期化する必要があることに注意してくださいitem.thumbnail。
Item item = new Item ();
item.thumbnail = new thumbnail();
プロパティを常に設定する必要がある場合は、次のようにクラスにコンストラクターを追加できます (サムネイルのセッターも削除し、クラスの名前を大文字にしました。クラス名は大文字で始める必要があります)。thumbnailItemThumbnail
public class Item
{
public Item(Thumbnail thumbnail)
{
if (thumbnail == null)
throw new ArgumentNullException("thumbnail");
this.thumbnail = thumbnail;
}
public string description { get; set; }
public string item_uri { get; set; }
public thumbnail thumbnail { get; }
}
Reflection を使用してプライベート プロパティを取得および設定する
リフレクションを使用するための例を次に示します。次のようなクラスがあるとします。
public class Test
{
private int PrivateInt
{
get;
set;
}
}
PrivateInt次のようにプロパティを設定および取得できます。
Test test = new Test();
var privateInt = test.GetType().GetProperty("PrivateInt", BindingFlags.Instance | BindingFlags.NonPublic);
privateInt.SetValue(test, 42); // Set the property.
int value = (int) privateInt.GetValue(test); // Get the property (will be 42).
ヘルパー メソッドで簡素化する
次のような一般的なヘルパー メソッドをいくつか記述することで、これを簡素化できます。
public static T GetPrivateProperty<T>(object obj, string propertyName)
{
return (T) obj.GetType()
.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.NonPublic)
.GetValue(obj);
}
public static void SetPrivateProperty<T>(object obj, string propertyName, T value)
{
obj.GetType()
.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.NonPublic)
.SetValue(obj, value);
}
次に、Testクラスの例は次のようになります。
Test test = new Test();
SetPrivateProperty(test, "PrivateInt", 42);
int value = GetPrivateProperty<int>(test, "PrivateInt");