c# 从 class 的新实例枚举值

c# enumerate values from new instance of a class

我早些时候在这里问了一个问题,但我没有正确解释,所以我得到了错误问题的正确答案。

我正在创建一个 class 的实例,当我得到 class 返回它时 returns 许多结果在 class 中是私有的打电话。

由于各种原因,我无法更改此 class 并使它们 public。

我需要做的是枚举并获取保存的 Text 变量的值:

public class StringReader
{

    private string LongText = "this is the text i need to return";
    private string Text;

    public StringReader()
    {

        Text = LongText;
    }
}

在方法中我试图获取我正在调用的 Text 的值

 StringReader sReader = new StringReader();
 List<StringReader> readers = new List<StringReader>() { sReader};

Readers 有 LongText 和 Text,但我正在努力取回文本值。

相反,它只是 returns 给我的类型。

不修改 class,就不可能使用最佳 OOP 实践。它们被设置为私有意味着它们只能在 class 内访问。您需要与 class 的原始开发人员交谈,询问他们为什么不能为私有字段制作 public getter,如下所示:

public string getText(){
    return this.Text;
}

这意味着无法修改字符串,但您至少可以读取它。

您将需要使用反射来访问私有字段。您可以使用 GetField(s) method. You can access their values using the GetValue function

访问一个类型的所有字段
public string GetLongText(StringReader reader)
{
    // Get a reference to the private field
    var field = reader.GetType().GetField("LongText", BindingFlags.NonPublic | 
                         BindingFlags.Instance)

    // Get the value of the field for the instance reader
    return (string)field.GetValue(reader);                 
}

声明为 private 的字段在定义它们的 class 之外是不可访问的。如果没有

,您将无法读取它们的值
  1. 改变他们的可见性
  2. 添加具有 public 可见性的访问器 method/property
  3. 使用反射(不推荐,几乎总有更好的方法)

这里的用例是什么?你想达到什么目的?如果您更笼统地定义您的问题,也许我们可以提供更好的解决方案。