Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我怎样才能得到一个财产';通过C#中的参数创建对象实例?_C#_Reflection_Instance Variables - Fatal编程技术网

我怎样才能得到一个财产';通过C#中的参数创建对象实例?

我怎样才能得到一个财产';通过C#中的参数创建对象实例?,c#,reflection,instance-variables,C#,Reflection,Instance Variables,如何通过C#中的参数获取属性的对象实例?我不确定它是否被称为变量实例,但我的意思是: 在通常情况下,当我们这样做时,我们会得到C#中变量的值: 我希望实现的是从类的属性中获取对象,比如说: void performOperation(ref Object property) { //so, what I hope to achieve is something like this: //Ideally, I can get the Pet object instance from

如何通过C#中的参数获取属性的对象实例?我不确定它是否被称为变量实例,但我的意思是:

在通常情况下,当我们这样做时,我们会得到C#中变量的值:

我希望实现的是从类的属性中获取对象,比如说:

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#中实现。我查看了反射API,但我仍然不确定应该使用什么来实现这一点


那么,当您将属性值传递给方法时,如何通过C#?

中的参数获取属性的对象实例,例如:

SomeMethod(obj.TheProperty);
SomeMethod(obj, obj.TheProperty);
然后将其实现为:

SomeType foo = obj.TheProperty;
SomeMethod(foo);
基本上,您无法从中获取父对象。您需要单独传递,例如:

SomeMethod(obj.TheProperty);
SomeMethod(obj, obj.TheProperty);

此外,请记住,值可以是任意数量对象的一部分。字符串实例可以用于零个、一个或“多个”对象。您所要求的基本上是不可能的。

我非常确定您必须将对象和属性传递到
performOperation
。因此,我无法仅从属性本身获取属性的对象实例?我不这样认为,至少您在示例中访问属性的方式是这样。我明白了。是的,在我的例子中,我访问属性的方式仅仅是我的智能的一个例子,因为我不确定我应该如何去做。我对C的语法也有些陌生。谢谢。:)如果您获得该属性的
属性info
。然后,可以使用获取声明成员的类,但看起来无法获取实例。