获取程序集名称的动态方法

huangapple go评论72阅读模式
英文:

How to obtain assembly name dynamically

问题

我有一个类在一个库中,像这样:

namespace Foo
{
    public abstract class EventBase
    {
        public string EventSource => Assembly.GetExecutingAssembly().GetName().Name;
        public long Timestamp => DateTimeOffset.UtcNow.ToUnixTimeSeconds();
        public Guid EventId => Guid.NewGuid();
    }
}

public class ActionRecordable : EventBase
{
    public string ActionName { get; set; }
    public Guid UserId { get; set; }
}

但当我在Bar解决方案中使用这个库时,属性EventSource返回的是Foo(库的命名空间),而不是使用它的项目的名称。

是否有任何方法可以动态获取正在使用的程序集的名称?

英文:

I got a class inside a library like this:

namespace Foo
{
 public abstract class EventBase
    {
        public string EventSource => Assembly.GetExecutingAssembly().GetName().Name;
        public long Timestamp => DateTimeOffset.UtcNow.ToUnixTimeSeconds();
        public Guid EventId => Guid.NewGuid();
    }
}
 public class ActionRecordable : EventBase
    {
        public string ActionName { get; set; }
        public Guid UserId { get; set; }
    }

But when I use the library in Bar solution, the property EventSource I got Foo (the namespace of the library instead of the name of the project that is using it).

Is there any way to get the name of the assembly that is being used dynamically?

答案1

得分: 2

你可以使用反射来获取程序集的名称,就像这样:

string name = System.Reflection.Assembly.GetEntryAssembly().GetName().Name;

英文:

You can get assembly name by using Reflection like this

 string name = System.Reflection.Assembly.GetEntryAssembly().GetName().Name;

答案2

得分: 2

以下是代码部分的翻译:

string name = System.Reflection.Assembly.GetExecutingAssembly().FullName;
string[] values = name.Split(new char[] { ',' });
Console.WriteLine("程序集全名:{0}", values[0]);
英文:

Here is the code which brings the name of the assembly at runtime<br>

string name =  System.Reflection.Assembly.GetExecutingAssembly().FullName;
string[] values = name.Split(new char[] { &#39;,&#39; });&lt;br&gt;
Console.WriteLine(&quot;FullName Assembly:{0}&quot;, values[0]);

huangapple
  • 本文由 发表于 2020年1月6日 21:58:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/59613423.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定