如何从外部程序集访问内部类? [英] How can I access an internal class from an external assembly?

查看:62
本文介绍了如何从外部程序集访问内部类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有一个我无法修改(供应商提供)的程序集,该程序集具有一个返回 object 类型但实际上是内部类型的方法。

Having an assembly which I cannot modify (vendor-supplied) which have a method returning an object type but is really of an internal type.

如何从程序集中访问对象的字段和/或方法?

How can I access the fields and/or methods of the object from my assembly?

请记住,我无法修改卖方提供的程序集。

Keep in mind that I cannot modify the vendor-supplied assembly.

本质上,这就是我所拥有的:

In essence, here's what I have:

来自卖方:

internal class InternalClass
  public string test;
end class

public class Vendor
  private InternalClass _internal;
  public object Tag {get{return _internal;}}
end class

public class MyClass
{
  public void AccessTest()
  {
    Vendor vendor = new Vendor();
    object value = vendor.Tag;
    // Here I want to access InternalClass.test
  }
}


推荐答案

如果无法访问类型(并且没有 InternalsVisibleTo等信息),则必须使用反射。但是更好的问题是:应该您正在访问此数据吗?它不是公共类型合同的一部分……在我看来,它打算被视为不透明的对象(出于其目的,而不是您的目的)。

Without access to the type (and no "InternalsVisibleTo" etc) you would have to use reflection. But a better question would be: should you be accessing this data? It isn't part of the public type contract... it sounds to me like it is intended to be treated as an opaque object (for their purposes, not yours).

您将其描述为公共实例字段;可以通过反射得到它:

You've described it as a public instance field; to get this via reflection:

object obj = ...
string value = (string)obj.GetType().GetField("test").GetValue(obj);

如果它实际上是财产(不是字段):

If it is actually a property (not a field):

string value = (string)obj.GetType().GetProperty("test").GetValue(obj,null);

如果它是非公开的,则需要使用 BindingFlags GetField / GetProperty 的重载。

If it is non-public, you'll need to use the BindingFlags overload of GetField/GetProperty.

重要事项:请谨慎进行此类反射;实现可能会在下一个版本中更改(破坏您的代码),或者可能被混淆(破坏您的代码),或者您可能没有足够的信任(破坏您的代码)。您发现模式了吗?

Important aside: be careful with reflection like this; the implementation could change in the next version (breaking your code), or it could be obfuscated (breaking your code), or you might not have enough "trust" (breaking your code). Are you spotting the pattern?

这篇关于如何从外部程序集访问内部类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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