【问题标题】:How to get class members without having access to Class type如何在没有访问类类型的情况下获取类成员
【发布时间】:2021-10-20 03:42:45
【问题描述】:

我有一个类 (Plug_Comment),其属性作为另一个类 (m_Descriptor) 的成员传递

我也可以获取类型

在里面我可以看到我需要的属性(没用),它是一个双属性

但我无法找到它,因为 Plug_Comment 类型在这里不知道,所以我无法转换它。

-----编辑----

我会再次尝试解释。很抱歉没有说清楚。

我想访问一个类的成员。 类类型是 Plug_Comment.Cplug_Comment 并且成员名称是双重无用的,它又在类属性中;

所以 namespace = Plug_Comment 在类 Plugin_Comment 内,在类 Properties 内和成员内 double useless 这就是我想要的。

然后,我从代码的另一部分获得上述属性,但将其转换为对象(见上文)。从那里看不到命名空间 Plug_Comment。所以我所拥有的只是对象,我不能将它转换为 Plug_Comment.PluginComment.Properties。

话虽如此,visual studio 清楚地显示(见图)该对象的类型为 Plug_Comment.properties。

这就是我尝试使用反射的原因。反思与否,我怎么能得到双重无用?

【问题讨论】:

  • 真的不清楚你在这里问什么。我什至不知道您为什么要尝试使用反射并弄乱类型。
  • 同意@DavidG。请发布您的代码的minimal, reproducible example,并说明您要实现的目标。截图不理想。
  • 我不知道你在做什么...m_Descriptor 是什么?它是如何以及在哪里声明的?你为什么尝试转换为不存在的类型Plug_Comment.CPlug_Comment.properties

标签: c# types reflection


【解决方案1】:

试试这个:

foreach (var item in m_Descriptor.Properties.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic))
{
    if (item.Name.Contains("useless"))
    {
        double myUseless = System.Convert.ToDouble (item.GetValue(m_Descriptor.Properties));
    }
}

您迭代所有字段(在您的情况下为 1),当名称正确时,您将获得值

【讨论】:

    【解决方案2】:

    我有一堂课(Plug_Comment)

    您没有 Plug_Comment 类。根据您的屏幕截图, Plug_Comment 是一个命名空间。它包含两个类; CPlug_Comment 类和 properties 类。 properties 类包含一个名为 useless 的属性。

    要访问一个名为 useless 的属性,该属性属于位于命名空间 Plug_Comment 中的名为 properties 的类,您可以这样做(示例包括创建类 properties 的实例):

    using Plug_Comment;
    
    var instanceOfProperties = new properties();
    double uselessValue = instanceOfProperties.useless;
    

    这是一个基于您问题中的第一个屏幕截图的示例:

    var a = m_Descriptor.Properties.useless;
    

    【讨论】:

    • 我无法使用 Plug_Comment 因为我看不到它
    【解决方案3】:

    Я также могу получить тип

    由此我们可以得出结论,变量aPlug_Comment 命名空间中的properties 类型。

    因此,变量可以强制转换为这种类型:

    Plug_Comment.properties prps = (Plug_Comment.properties) a;
    

    或者:

    using Plug_Comment;
    
         properties prps = (properties) a;
    

    在这种转换之后,“属性”类型的所有公共成员都将可供您使用。 可以获取和设置属性值,调用方法。

    double num = prps.useless;
    prps.useless = 123.456;
    

    如果“属性”类型是私有的或内部的,编译器会在这种转换上产生错误。 如果存在该错误,请显示其全文。 在这种情况下,您将不得不使用反射来处理非公共类。

    【讨论】:

      猜你喜欢
      • 2011-07-06
      • 1970-01-01
      • 1970-01-01
      • 2019-12-18
      • 2012-08-16
      • 2013-09-20
      • 2022-08-17
      • 2018-04-02
      • 2021-08-30
      相关资源
      最近更新 更多