如何正确创建在C#中返回Type的方法(Java到C#转换)

bje*_*ski 1 c# java types

我目前正致力于将一些代码从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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

我很难将其翻译成C#.到目前为止,我最好的努力看起来与此类似:

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

所以我设法处理了Enum转变为公共密封类的事实:

public sealed class DataType
    {
        public static readonly DataType BooleanType = new DataType(); ...
Run Code Online (Sandbox Code Playgroud)

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

Dan*_*rth 5

你需要typeof,即

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

哦,C#也支持枚举:

public enum DataType
{
    Boolean,
    String,
    Integer
}
Run Code Online (Sandbox Code Playgroud)

用法是:

case DataType.String:
    return typeof(string);
Run Code Online (Sandbox Code Playgroud)

更新:

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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

用法如下:

var dataType = DataType.Boolean;
var type = dataType.GetCsharpDataType();
Run Code Online (Sandbox Code Playgroud)