gpt4 book ai didi

c# - 如何根据项目中的类制作枚举变量

转载 作者:太空宇宙 更新时间:2023-11-03 23:47:01 24 4
gpt4 key购买 nike

我正在编写一个 DLL,它将公开这样一个方法:

public static void Convert(string inputFile, string outputFile, FileType fileType)

目前,FileType 是一个像这样公开的枚举:

public enum FileType
{
ConvertClassOne,
ConvertClassTwo,
ConvertClassThree
}

这将代表可以转换给定类型文件的每个类。我将有几个基于接口(interface)的不同类,每个类都可以处理特定类型的文件。

我不想像上面那样有一个枚举,每次我添加一个类时我都必须手动更改它,以便调用程序可以告诉我他们给我的文件类型,我想公开一个根据我的项目中具有给定属性的类自动更改自身的枚举。

所以如果我添加一个具有给定属性的类:

[SomeAttribute]
public class NewClassAdded()
{
}

FileType 枚举将选择它并且调用程序将能够看到

FileType.NewClassAdded

无需我手动更改任何其他内容。我很确定反射将允许我编写一个方法来返回具有给定属性的每个类的名称,但我不确定具体如何,也不知道我将如何将这些名称公开为枚举。

谢谢,

安德鲁

最佳答案

这可能不是您正在寻找的答案,但您是否考虑过使用泛型?它将解决您可以添加新功能的问题。您可以使用代表您的枚举的接口(interface)。对于每个枚举值,都会有一个实现该接口(interface)的类。每当您想添加一个新选项时,只需添加一个实现该接口(interface)的新类。您可以在这些类中添加额外的功能,或者您可以将它们用作枚举值的替代品(下面代码中的变体 1 和 2)。示例:

class Program
{
static void Main(string[] args)
{
Converter.Convert("input", "output", new FormatA());
Converter.Convert("input", "output", new FormatB());
}
}

class Converter
{
public static void Convert<T>(string inputFile, string outputFile, T formatter) where T : IConvertFormat
{
// First variant: Keep the functionality in the formatter object

formatter.DoSomething(inputFile, outputFile);

// Second variant: check for the actual type

if (formatter is FormatA)
{
// ... do format A
}
else if (formatter is FormatB)
{
// ... do format B
}
}
}

interface IConvertFormat
{
// Method not required for variant 2
void DoSomething(string inputFile, string outputFile);
}

class FormatA : IConvertFormat
{
public void DoSomething(string inputFile, string outputFile)
{
// .. do it like Format A (not required for variant 2)
}
}

class FormatB : IConvertFormat
{
public void DoSomething(string inputFile, string outputFile)
{
// do it like Format B (not required for variant 2)
}
}

附言。我认为这基本上就是@Jauch 的提议。

关于c# - 如何根据项目中的类制作枚举变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27320695/

24 4 0
文章推荐: c# - 带有 List 的 JSON.NET 的 System.OutOfMemoryException