[英]How can I get a property's object instance through a parameter in C#?
如何通過C#中的參數獲取屬性的對象實例? 我不確定是否將其稱為變量實例,但這是我的意思:
在通常情況下,執行此操作時,將獲得C#中變量的值:
void performOperation(ref Object property) {
//here, property is a reference of whatever was passed into the variable
}
Pet myPet = Pet();
myPet.name = "Kitty";
performOperation(myPet.name); //Here, what performOperation() will get is a string
我希望實現的是從類的屬性中獲取對象,例如:
void performOperation(ref Object property) {
//so, what I hope to achieve is something like this:
//Ideally, I can get the Pet object instance from the property (myPet.name) that was passed in from the driver class
(property.instance().GetType()) petObject = (property.instnace().GetType())property.instance();
//The usual case where property is whatever that was passed in. This case, since myPet.name is a string, this should be casted as a string
(property.GetType()) petName = property;
}
Pet myPet = Pet();
myPet.name = "Kitty";
performOperation(myPet.name); //In this case, performOperation() should be able to know myPet from the property that was passed in
instance()
只是一個虛擬方法,用以演示我要獲取屬性的實例對象。 我是C#的新手。 從概念上講,這是我希望實現的目標,但是我不確定如何在C#中實現。 我瀏覽了Reflection API,但仍然不確定應該使用什么功能。
那么,如何通過C#中的參數獲取屬性的對象實例?
將屬性值傳遞給方法時,例如:
SomeMethod(obj.TheProperty);
然后將其實現為:
SomeType foo = obj.TheProperty;
SomeMethod(foo);
基本上,您不能從中獲得父對象。 您將需要分別傳遞它,例如:
SomeMethod(obj, obj.TheProperty);
此外,請記住,值可以是任意數量的對象的一部分。 字符串實例可用於零個,一個或“許多”對象中。 您所要求的基本上是不可能的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.