我想获取入口程序集的名称,例如 myApp.exe。以前在 net45 中,我会使用 Assembly.GetEntryAssembly,但这在 Profile 158 中不可用。是否有其他选择? (我可以一直链回 Assembly.GetCallingAssembly 吗?)非常感谢任何提示。
使用 GetEntryAssembly,我可以确定应用程序的名称。我将此名称用于 HttpClient 调用中的 UserAgent,以及命名文件和标记原始应用程序的反馈。获取应用程序名称的替代方法将不胜感激。
最佳答案
To get the name of the application
您将不得不面对一个严峻的事实,即 Assembly.GetEntryAssembly() 在商店和电话应用程序中不可用。所以你也不可用,你的图书馆无法在这样的应用程序中工作。缺少 .NET Framework 支持可能很难找到变通办法,但这很容易。无论什么应用程序使用您的库,都可以毫不费力地为您提供这些信息。要么是因为它没有使用 GetEntryAssembly() 的限制,要么是因为它知道它的逻辑名称是什么。
所以只要公开一个属性让客户端程序员告诉你就行了。只需提供一个 Really Good 异常消息,这样他就会在忘记时立即知道。像这样的东西:
public static string ApplicationName {
get {
if (_applicationName == null) {
throw new InvalidOperationException("You *must* assign the ApplicationName property before this library is usable");
}
return _applicationName;
}
set { _applicationName = value; }
}
private static string _applicationName;
请务必在您自己的代码中使用该属性而不是私有(private)字段,以便可靠地引发异常。
因此,现在商店应用程序程序员只需在其应用程序构造函数中对属性分配进行硬编码:
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
YourPclLibrary.ApplicationName = "MyBeautifulSoup";
// etc...
}
允许客户端程序员通过类构造函数传递应用程序名称当然也是一种完全合法(并且更可取)的方法。
关于c# - 来自可移植类库的 GetEntryAssembly(配置文件 158),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20555457/