java - 如何在 C# 中实现动态泛型类型返回方法而不需要在运行时进行强制转换?

标签 java c#

假设我想将下面的 Java 实现转换为 C#,这样我就不必在运行时转换返回值,而转换应该已经在 get 方法中处理。

如果你问的话,为什么不创建 setter 和 getter?只是因为我计划拥有 50-100 多个属性,并且我不想为每个属性创建 setter 和 getter。

[c#] - 我最终想用 c# 做什么

string name = playerA.getAttribute(Attribute.NAME);
int age = playerA.getAttribute(Attribute.AGE);

目前我不能,除非我将返回的值转换为正确的类型。但是我可以在返回之前在 get 方法中进行强制转换吗?

[Java] - 无论如何,这是当前无需强制转换即可工作的 java 实现

//setting attributes
playerA.setAttribute(Attribute.NAME, "Tom");
entityB.setAttribute(Attribute.AGE, 4);
...
//getting the attribute without casting
string name = playerA.getAttribute(PlayerAttribute.NAME);
int age = playerB.getAttribute(PlayerAttribute.AGE);

玩家/实体内部的方法是这样设置的以获取属性
[Java]

public <E> E getAttribute(Attribute attr){
    //atrributeRepository is EnumMap<Attribute, Object>
    //how I will get my attribute value type at runtime
    Object result = attributeRepositoryMap.get(attr);

    //the enumMap will only ever hold these three type for this example
    if(result instanceof Boolean){ return (E) (Boolean) result; }
    if(result instanceof String){ return (E) (String) result; }
    if(result instanceof Integer){ return (E) (Integer) result; }

    return null;    
    //say all checks are in place and null will never be reach
}

我能在 C# 中得到的最接近的是这个。

[c#] - 虽然我可以处理它,但我想阻止转换

string name = (string) getAttribute<string>(Attribute.NAME);
int age = (int) getAttribute<int>(Attribute.AGE);

方法

public T getAttribute<T>(Attribute attribute){
{
     Object result = attributeRepositoryDictionary[attribute];
     return (T)result;
}

这是我能用 C# 得到的最接近的结果吗,需要进行强制转换才能获取属性?

最佳答案

我不确定我是否真的喜欢它作为一个想法 - 但你可以通过使 Attribute 通用来做到这一点:

public static class Attributes
{
    public static Attribute<int> Age = new Attribute<int>("age");
    public static Attribute<string> Name = new Attribute<string>("name");
}

public class Attribute<T>
{
    public string Key { get; }

    public Attribute(string key)
    {
        Key = key;
    }

    ...
}

然后你可以将你的方法实现为:

public T GetAttribute<T>(Attribute<T> attribute)
{
    // attributeDictionary would be a Dictionary<string, object>
    return (T) attributeDictionary[attribute.Key];
}

那时,类型推断将成为您的 friend ,因此您可以编写:

int a = player1.GetAttribute(Attributes.Age);

它相当于:

int a = player1.GetAttribute<int>(Attributes.Age);

关于java - 如何在 C# 中实现动态泛型类型返回方法而不需要在运行时进行强制转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31630294/

相关文章:

java - 这个锁管理代码片段是否过于复杂?

java - 如何避免 ArrayIndexOutOfBounds?

c# - 通过简单注入(inject)器拦截/装饰 Entity Framework 的 DbContext.SaveChanges()

c# - WPF 列表框绑定(bind)

C#连接变为空

java - 如何使用JCreator (Pro)设置执行目录?

java - 从 Android 中的 x.509 证书中获取 CA 详细信息

没有 Devcon 的 C# Devcon 功能?

java - 终止 mvn spring-boot :run doesn't stop tomcat

c# - 使用 SqlDataAdapter 计算行数