Assembly.GetCallingAssembly不支持WinRT的,但对于便携式类库?(Ass

2019-08-08 00:30发布

我需要得到一些元数据约这就要求我的组件装配。 因此,使用Assembly.GetCallingAssembly()似乎是天作之合。 然而,我发现它的工作原理无处不在,除了在Windows应用商店。 在那里的支持:

  • 电话7.0+
  • .NET 1.0+
  • 便携式类库

但是,如果它不直接支持的操作系统是Windows Store应用程序中。 我可以做一个便携式类库,然后调用它从那里的Windows Store应用程序里面,但我不能只把它直接在Windows应用商店的应用程序/类库。

有没有一种解决方法或一些其他的方式来获得所提供的元数据的类型Assembly

Answer 1:

Assembly.GetCallingAssembly没有暴露在WinRT中-据说是因为它的语义是内联等(面对不可靠的来源 ),但它也并不适合过多在Windows Store应用程序允许受限制的反映。 你可以像Assembly.GetCurrentAssembly()例如,像这样的:

typeof(MainPage).GetTypeInfo().Assembly

但是,这不一样的。 与受限制的反射模型,在运行时获得栈跟踪如在.NET可能将是不可能的任一。

至于便携式类库,我正要说Assembly.GetCurrentAssembly()在一般的便携式类库支持,但只是没有在WinRT中-这将使意义,如果它根本就不在该平台。 但实际上,它似乎是存在于所有配置文件包括除了WinRT的+ .NET4.5的WinRT - 它似乎必须有某种形式的监督,在这里与此不一致。 因此,该方法目前在WinRT中(而且没有排序重定向回事),但可在编译时元数据不可见。

因此,你可以调用与反思的方法:

var assembly = (Assembly) typeof(Assembly).GetTypeInfo()
    .GetDeclaredMethod("GetCallingAssembly")
    .Invoke(null, new object[0]);

我相信在Windows应用商店中的应用程序这种方法的不可见性是“我们希望这将消失”。

(这个答案涉及“我可以”而不是“我应该”)。



Answer 2:

The method was cut simply because it is too unreliable in a WinRT app. A strong design goal for WinRT was to make interop between different language runtime environments simple and trouble-free. Which works well, you can easily create a WinRT component in a language like C# and have it used by an app that was written in an unmanaged language like C++ or Javascript.

This is possible as well in a desktop .NET app but it is much more complicated, having to fall back to a [ComVisible] assembly or creating a mixed-mode assembly in the C++/CLI language. Using Assembly.GetCallingAssembly() in such a case will fail as well, it is however entirely expected to fail by the programmer since he's well aware of doing something special.

That gets a lot more murky in a WinRT component. Especially since it doesn't necessary fail if the call was actually made from another .NET assembly. But no hope when it came from unmanaged code.

This random kind of failure is just utter misery without a decent workaround. Accordingly the method was cut. Using PCL is a possible workaround, but Microsoft has sternly warned in the past that such kind of hackorama is highly unrecommended. With non-zero odds that it will be caught by the store validation procedure and result in a rejection.



文章来源: Assembly.GetCallingAssembly isn't supported on WinRT, but is for portable class libraries?