gpt4 book ai didi

c# - 预处理器 : Get Operating System . 网络核心

转载 作者:行者123 更新时间:2023-12-04 01:52:33 28 4
gpt4 key购买 nike

我正在编写一个我希望在 Windows 和 Linux 上都使用的类。

此类中的方法之一是访问 Windows Registry

我希望实现的是在使用 Linux 机器时以某种方式禁止使用这种特殊方法。

首先我做了一些研究,看看是否有是 .Net Core 的东西这将允许我检查正在使用的操作系统,我发现 this并且确实有效。

当我在访问方法时将其实现到我的代码中时,我希望禁用正在访问 Windows 注册表的方法,但是我最接近的方法是使用switch 语句,像这样

switch (OS)
{
case OSX:
return;

case LINUX:
return
}

如果操作系统不受支持,返回,这是有效的,但是我后来认为禁用它一起访问会更好,而不是为不支持的操作系统抛出错误对于那个特定的方法

然后我继续查看preprocessor directives认为如果我能够根据框架等检测和禁用部分代码,也许我可以使用类似的东西来根据操作系统禁用部分代码,这样即使在尝试访问该方法时也永远不会调用它们

我从那里继续查看是否可以使用预处理器指令禁用部分代码。
我找到了this。 .

我知道这是为了C++然而,它似乎是我能找到的最接近我在 .Net Core 中尝试实现的目标

在一个完美的世界中,它看起来像这样

    /// <summary>
/// Get the file mime type
/// </summary>
/// <param name="filePathLocation">file path location</param>
/// <returns></returns>
`#if WINDOWS`
public static string GetMimeType(this string filePathLocation)
{
if (filePathLocation.IsValidFilePath())
{
string mimeType = "application/unknown";
string ext = Path.GetExtension(filePathLocation).ToLower();
Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);

if (regKey != null && regKey.GetValue("Content Type") != null)
{
mimeType = regKey.GetValue("Content Type").ToString();
}
return mimeType;
}
return null;
}
`#endif`

我确实看到了 #Define 所以我尝试了类似这样的东西 #define IS_WINDOWS 并将它与 #if IS_WINDOWS 一起添加到我的类中但是,如果我希望一遍又一遍地重用静态类,我看不出如何更改该值。

最佳答案

虽然您可以采用涉及 #define 的路线,但这是编译时,您将失去很多 .Net 的多平台优势。您还必须兼顾多种配置、多种构建等。

在可能的情况下,将依赖于平台的行为隐藏在独立于平台的抽象之后,并在运行时使用 System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform 进行检查。 :

interface IPlatform
{
void DoSomething();
}

class WindowsImpl : IPlatform
{
public void DoSomething()
{
// Do something on Windows
}
}

class LinuxImpl : IPlatform
{
public void DoSomething()
{
// Do something on Linux
}
}

// Somewhere else
var platform = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? new WindowsImpl() : new LinuxImpl();
platform.DoSomething();

这适用于很多事情,包括 PInvoke .您将能够在任一平台上使用相同的二进制文件,并且以后添加 OSX 会更容易。

如果您需要在编译时隔离与平台相关的代码(可能一个包仅适用于 Windows),MEF2/System.Composition可以帮助您制作一个插件框架,其中每个平台都有自己的程序集:

// In Windows.dll class library project
using System.Composition;

[Export(typeof(IPlatform))]
public class WindowsImpl : IPlatform
{
public void DoSomething()
{
//...
}
}

然后在你的主程序中:

using System.Composition.Hosting;

var configuration = new ContainerConfiguration();
var asm = Assembly.LoadFrom(pathToWindowsDll);
configuration.WithAssembly(asm);
var host = configuration.CreateContainer();
var platform = host.GetExports<IPlatform>().FirstOrDefault();

关于c# - 预处理器 : Get Operating System . 网络核心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52295448/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com