gpt4 book ai didi

c# - 如何在 C# 中通过参数获取属性的对象实例?

转载 作者:太空宇宙 更新时间:2023-11-03 13:53:42 24 4
gpt4 key购买 nike

如何在 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);

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

关于c# - 如何在 C# 中通过参数获取属性的对象实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12996303/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com