如何存储对 Class 属性的引用并通过它访问实例的属性? [英] How to store reference to Class' property and access an instance's property by that?

查看:47
本文介绍了如何存储对 Class 属性的引用并通过它访问实例的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何保持类属性的某种链接,然后使用它来访问实例的属性?问题是没有创建链接的类实例.这个想法是在访问任何实例之前记住该属性.

How do I keep some sort of link to a class' property and then use that to access an instance's property? Thing is there are no class instances where the link is created. The idea is to remember the property before any instances can be accessed.

这是一个例子:

Class A { int integer { get; set; }  }

var link = GetLink(A.integer); // implementetion of GetLink(???) is unknown

MyMethod(link);

void MyMethod(??? link)
{
    A a = new A();
    int i = GetValueByLink(a, link); // this is also undefined
}

有没有办法在 C# 中做这样的事情?

Is there a way to do something like this in C#?

推荐答案

看起来你正在寻找 Reflection

示例:

public class A
{
  int integer{get; set;}
}

PropertyInfo prop = typeof(A).GetProperty("integer");
A a = new A();
prop.GetValue(a, null);
prop.SetValue(a, 1234, null);

您仍然需要对 set/get 值的引用,但这似乎是您想要的.

You still need a reference to set/get values, but this seems about what you're wanting.

这篇关于如何存储对 Class 属性的引用并通过它访问实例的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆