在PCL中获取装配版本

时间:2013-05-13 08:53:24

标签: .net-assembly portable-class-library system.reflection

我在.NET 4.5中有以下代码行,我正在尝试构建为可移植类库。它的目的是获得汇编版本:

this.GetType().Assembly.GetName().Version.Major;

问题是PCL中没有Assembly.GetName()。有没有办法在PCL中获得汇编版本?

我知道可以解析Assembly.FullName,但我想要一个更好的解决方案。

3 个答案:

答案 0 :(得分:22)

    public static string Version
    {
        get
        {
            var assembly = typeof(MyType).GetTypeInfo().Assembly;
            // In some PCL profiles the above line is: var assembly = typeof(MyType).Assembly;
            var assemblyName = new AssemblyName(assembly.FullName);
            return assemblyName.Version.Major + "." + assemblyName.Version.Minor;
        }
    }

答案 1 :(得分:7)

我现在使用以下内容:

[assembly: AssemblyTitle(AssemblyInfo.AssemblyTitle)]
[assembly: AssemblyProduct(AssemblyInfo.AssemblyProduct)]

[assembly: AssemblyVersion(AssemblyInfo.AssemblyVersion)]
[assembly: AssemblyFileVersion(AssemblyInfo.AssemblyFileVersion)]
[assembly: AssemblyInformationalVersion(AssemblyInfo.AssemblyInformationalVersion)]

internal class AssemblyInfo
{
    public const string AssemblyTitle = "...";
    public const string AssemblyProduct = "...";

    public const string AssemblyVersion = "1.0.0.0";
    public const string AssemblyFileVersion = "1.0.0.0";
    public const string AssemblyInformationalVersion = "1.0.0.0-dev";
}

这允许我在不使用反射的情况下引用组件中的任何常量,例如AssemblyInfo.AssemblyProduct

答案 2 :(得分:2)

您的目标是基于Silverlight的平台(Silverlight 4或更高版本,Windows Phone 8之前的版本)。那些平台没有“支持GetName()方法。对于这些平台,您可以定义这样的扩展方法:

public static class AssemblyExtensions
{
    public static AssemblyName GetName(this Assembly assembly)
    {
        return new AssemblyName(assembly.FullName);
    }
}