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

时间:2013-09-12 12:49:58

标签: 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;
        }
    }

我很难将其翻译成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指定吗?)。有人知道这个功能更优雅的实现吗?

3 个答案:

答案 0 :(得分: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();

答案 1 :(得分: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;
    }
}

答案 2 :(得分:1)

除非转换为类型名称,否则无法使用Switch语句。

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

        }
        return null;