gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:33:40 25 4
gpt4 key购买 nike

我目前正致力于将一些代码从 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)密封类的事实:

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

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

最佳答案

你需要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();

关于c# - 如何在 C# 中正确创建返回类型的方法(Java 到 C# 的转换),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18764800/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com