我怎样才能访问这个属性?

时间:2015-02-10 12:50:14

标签: c#

我想获得Rectangle的值,如下图所示,

enter image description here

我做了一些谷歌搜索,但我唯一能找到的是我可以访问属性而不是对象,

I need to access a non-public member (Highlighted Item) of a Combo Box

我顺便使用Aspose.Pdf.Cell。

3 个答案:

答案 0 :(得分:7)

Rectangle这里似乎是班级Aspose.Pdf.Text.TextFragment的公共财产。所以,可能你可以使用类型转换来获取它:

var fragment = d.Paragraphs[0] as TextFragment;
if(fragment!=null) 
{
    var rect = fragment.Rectangle
}

我没有尝试过,但根据文档,Paragraphs indexerRectangle属性都是公开的。 IDE中的“非公共成员”消息涉及Paragrpaphs对象的内部数组,该数组通过此调试器会话中的反射进行访问。

答案 1 :(得分:2)

var paragraph = d.Paragraphs.FirstOrDefault(); // or [0] if you're not using Linq
var pInfo = paragraph.GetType().GetProperties(BindingFlags.Instance | BindingFlags.NonPublic).FirstOrDefault(p => p.Name == "Rectangle");
if(pInfo != null)
{
    var val = pInfo.GetValue(paragraph) as Rectangle; // or whatever the actual type of that property is
}

使用反射可以读取和写入您可能无法访问的值。这里唯一需要注意的是,它不能成为私人会员。

但如果此属性是公开的,如上所述,您应该绝对浏览实际对象的公开API,而不是这样做。

答案 2 :(得分:0)

正如@ William-Custode所指出的那样,与私人财产互动可能会产生意想不到的副作用,因为它们通常因某种原因而被私有化。但是,有时需要进行调试或测试。如果需要访问值1,可以通过反射机制来实现,如下所示:

using System;
using System.Reflection;

public class Example
{
    public int PublicProp { get { return 10; } }

    private int PrivateProp { get { return 5; } }
}

public class Program
{
    public static void Main()
    {
        Example myExample = new Example();

        Console.WriteLine("PublicProp: " + myExample.PublicProp);

        PropertyInfo[] properties = typeof(Example).GetProperties(BindingFlags.Instance | BindingFlags.NonPublic);

        foreach (PropertyInfo prop in properties)
        {
            Console.WriteLine(prop.Name + ": " + prop.GetValue(myExample));
        }

        Console.ReadKey();
    }
}
相关问题