C#中 - 如何从外部装配访问内部类 [英] C# - How to access internal class from external assembly

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

问题描述

说完,我不能修改(附送供应商),其中有返回的方法组装的 对象类型,但确实是一个内部的类型。

我如何可以访问域和/或对象的方法,从我的组装?

请记住,我不能修改供应商提供的组件。

在本质上,这是我有:

从供应商:

 内部类InternalClass
  公共字符串试验;
末级公共类供应商
  私人InternalClass _internal;
  公共对象标记{{返回_internal;}}
末级

从使用供应商组装我的程序集。

 公共类MyClass的
{
  公共无效AccessTest()
  {
    厂商厂商=新的供应商();
    对象值= vendor.Tag;
    //这里我想访问InternalClass.test
  }
}


解决方案

如果无法访问类型(以及没有InternalsVisibleTo等),你将不得不使用反射。但是,一个更好的问题应该是:的你可以访问这些数据?这不是大众型合同的一部分......这听起来好像它的目的是被视为一个不透明的对象(他们的目的,不是你的)。

您已经将其描述为一个公共实例字段;通过反射得到这样的:

  obj对象= ...
字符串值=(字符串)obj.GetType()getfield命令(测试)的GetValue(OBJ)。

如果它实际上是一个属性(而不是字段):

 字符串值=(字符串)obj.GetType()的getProperty(测试)的GetValue(OBJ,NULL);

如果它是非公开的,你需要使用 getfield命令 / <$的的BindingFlags 超载C $ C>的getProperty 。

重要预留:要小心这样的反映;实现可能在未来的版本中改变(破坏你的code),也可以进行模糊处理(破坏你的code),或者你可能没有足够的信任(破坏你的code)。你是否察觉模式?

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:

From vendor:

internal class InternalClass
  public string test;
end class

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

From my assembly using the vendor assembly.

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

解决方案

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);

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?

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

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