我的程序通过 Win32API 函数与操作系统进行大量交互。现在我想将我的程序迁移到Linux下的Mono下运行(没有wine),这需要不同的实现来与操作系统的交互。
我开始设计一个代码,它可以针对不同的平台有不同的实现,并且可以为新的未来平台扩展。
public interface ISomeInterface
{
void SomePlatformSpecificOperation();
}
[PlatformSpecific(PlatformID.Unix)]
public class SomeImplementation : ISomeInterface
{
#region ISomeInterface Members
public void SomePlatformSpecificOperation()
{
Console.WriteLine("From SomeImplementation");
}
#endregion
}
public class PlatformSpecificAttribute : Attribute
{
private PlatformID _platform;
public PlatformSpecificAttribute(PlatformID platform)
{
_platform = platform;
}
public PlatformID Platform
{
get { return _platform; }
}
}
public static class PlatformSpecificUtils
{
public static IEnumerable<Type> GetImplementationTypes<T>()
{
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
foreach (Type type in assembly.GetTypes())
{
if (typeof(T).IsAssignableFrom(type) && type != typeof(T) && IsPlatformMatch(type))
{
yield return type;
}
}
}
}
private static bool IsPlatformMatch(Type type)
{
return GetPlatforms(type).Any(platform => platform == Environment.OSVersion.Platform);
}
private static IEnumerable<PlatformID> GetPlatforms(Type type)
{
return type.GetCustomAttributes(typeof(PlatformSpecificAttribute), false)
.Select(obj => ((PlatformSpecificAttribute)obj).Platform);
}
}
class Program
{
static void Main(string[] args)
{
Type first = PlatformSpecificUtils.GetImplementationTypes<ISomeInterface>().FirstOrDefault();
}
}
我看到这个设计有两个问题:
- 我不能强制
ISomeInterface
实现PlatformSpecificAttribute
. - 多个实现可以用相同的标记
PlatformID
,我不知道在 Main.js 中使用哪个。使用第一个是 ummm 丑陋的。
如何解决这些问题?你能推荐另一种设计吗?