一个属性参数必须是一个常量表达式在C#中有这种方法吗?

时间:2010-02-23 19:36:25

标签: c# .net-3.5 unrar

我正在使用涉及使用unrar的代码(WinForms C#NET 3.5)。

    [DllImport("UNRAR64.DLL")]
    private static extern IntPtr RAROpenArchive(ref RAROpenArchiveData archiveData);
    [DllImport("UNRAR64.DLL")]
    private static extern IntPtr RAROpenArchiveEx(ref RAROpenArchiveDataEx archiveData);
    [DllImport("UNRAR64.DLL")]
    private static extern int RARCloseArchive(IntPtr hArcData);
    [DllImport("UNRAR64.DLL")]
    private static extern int RARReadHeader(IntPtr hArcData, ref RARHeaderData headerData);
    [DllImport("UNRAR64.DLL")]
    private static extern int RARReadHeaderEx(IntPtr hArcData, ref RARHeaderDataEx headerData);
    [DllImport("UNRAR64.DLL")]
    private static extern int RARProcessFile(IntPtr hArcData, int operation, [MarshalAs(UnmanagedType.LPStr)] string destPath, [MarshalAs(UnmanagedType.LPStr)] string destName);
    [DllImport("UNRAR64.DLL")]
    private static extern void RARSetCallback(IntPtr hArcData, UNRARCallback callback, int userData);
    [DllImport("UNRAR64.DLL")]
    private static extern void RARSetPassword(IntPtr hArcData, [MarshalAs(UnmanagedType.LPStr)] string password);

由于我希望代码在32BIT和64BIT上工作,我想通过字符串unrarDll分配UNRAR64.DLL或UNRAR.DLL,具体取决于检查系统的位数。

    private void DllChoice() {
        if (SystemIs64Bit()) {
            sevenZipDll = "7z-x64.dll";
            unrarDll = "unrar.dll";
        } else {
            sevenZipDll = "7x-x32.dll";
            unrarDll = "unrar64.dll";
        }
    } 
    private static bool SystemIs64Bit() {
        return (IntPtr.Size == 8);
    }

抛出错误:

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

这有简单的方法吗?这样做的正确方法是什么?

2 个答案:

答案 0 :(得分:7)

不:-)这是规范的一部分......你必须为每个平台(x86 / x64)分别建立两个版本。你可以做的只是定义一个预处理器指令,然后执行类似

的操作
#if x64
// ... define all x64 imports here
#else
// ... define all x86 imports here
#endif

答案 1 :(得分:4)

为unrar导入创建接口,并分别实现32位和64位版本。如果是32位,则实例化32位impl,否则实例化64位impl。