1

我目前正在将一些代码从 Java 移植到 C#。

我遇到了一个在 Java 中不太难的代码问题:

public static Object getJavaDataType(DataType dataType) {
        switch (dataType) {
        case Boolean:
            return Boolean.class;
        case Date:
            return java.util.Date.class;
        case Integer:
            return Integer.class;
        case String:
            return String.class;
        default:
            return null;
        }
    }

我在将其翻译成 C# 时遇到了困难。到目前为止,我的最大努力看起来与此类似:

public static Type getJavaDataType(DataType dataType) {
            if(dataType == BooleanType){
                return Type.GetType("Boolean");
            } else if ...

因此,我设法处理了将 Enum 转换为公共密封类的事实:

public sealed class DataType
    {
        public static readonly DataType BooleanType = new DataType(); ...

但是类型代码对我来说看起来不正确(真的必须由 String 指定吗?)。有人知道这个功能的更优雅的实现吗?

4

3 回答 3

5

你需要typeof,即

  • typeof(bool)
  • typeof(int)
  • typeof(string)
  • typeof(DateTime)

哦,C# 也支持枚举:

public enum DataType
{
    Boolean,
    String,
    Integer
}

用法是:

case DataType.String:
    return typeof(string);

更新:

不要使用带static readonly字段的类,因为您需要向枚举添加方法,您可以使用扩展方法来代替。

它看起来像这样:

public enum DataType
{
    Boolean,
    String,
    Integer
}

public static class DataTypeExtensions
{
    public static Type GetCsharpDataType(this DataType dataType)
    {
        switch(dataType)
        {
            case DataType.Boolen:
                return typeof(bool);
            case DataType.String:
                return typeof(string);
            default:
                throw new ArgumentOutOfRangeException("dataType");
        }
    }
}

用法是这样的:

var dataType = DataType.Boolean;
var type = dataType.GetCsharpDataType();
于 2013-09-12T12:51:20.877 回答
1

这是 C# 中枚举的下注示例:

public enum DataType
{
    Boolean,
    Date,
    Integer,
    String
}

这里是你的方法:

public static Type getJavaDataType(DataType dataType)
{
    switch (dataType)
    {
        case DataType.Boolean:
            return typeof(bool);
        case DataType.Date:
            return typeof(DateTime);
        case DataType.Integer:
            return typeof(int);
        case DataType.String:
            return typeof(string);
        default:
            return null;
    }
}
于 2013-09-12T12:58:22.587 回答
1

除非转换为类型名称,否则使用 Switch 语句是不可能的。

        switch (dataType.GetType().Name)
        {
            case "TextBox":
                break;

        }
        return null;
于 2013-09-12T13:30:47.923 回答