在泛型方法中从字典获取键和值类型 [英] Get Key and Value types from dictionary in generic method

查看:98
本文介绍了在泛型方法中从字典获取键和值类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够在泛型方法中使用字典。我正在寻找的是一种方法来获得类型从发送到泛型扩展方法LoadProperty的字典的键和值。



这是我迄今为止所做的。



我将该方法称为扩展

  entityObject.LoadProperty< ;字典< string,int>>(CartonThreshold)
//entityObject.LoadProperty& Dictionary& String,double>>(CartonThreshold)

// ...

public static T LoadProperty< T>(EntityObject entity,string name)where T:new()
{
EntityObjectProperty prop = entity.Properties.Single(x => ; x.Name.Equals(name));

//如果请求字典
if(typeof(T).GetInterface(typeof(IDictionary<,>)。Name)!= null || typeof(T).Name.Contains (IDictionary))
{
var dictionaryInstance =(IDictionary)new T();

//仅用于测试
var a = dictionaryInstance.Keys.GetType()。Name;
var b = dictionaryInstance.Values.GetType()。Name;

var key =(T)Convert.ChangeType(prop.Name,typeof(T));
var value =(T)Convert.ChangeType(prop.Value,typeof(T));
dictionaryInstance.Add(key,value);
return(T)dictionaryInstance;
}

//默认
return(T)Convert.ChangeType(prop.Value,typeof(T));

$ / code>

目标是返回一个正确类型的字典

解决方案

我在找的是GetType()的GetGenericArguments()扩展

下面将返回我需要的。

  public static T LoadProperty< T>(此EntityObject实体,字符串名称)其中T:new ()
{
EntityObjectProperty prop = entity.Properties.Single(x => x.Name.Equals(name));

try
{
//如果请求字典
if(typeof(T).GetInterface(typeof(IDictionary<,>)。Name)!= null || typeof(T).Name.Contains(IDictionary))
{
var dictionaryInstance =(IDictionary)new T();

var typing = dictionaryInstance.GetType()。GetGenericArguments();
键入keyType =输入[0];
类型valueType =打字[1];

//字典后备,设置为value的默认值如果为null
object value = prop.Value!= null? Convert.ChangeType(prop.Value,valueType):Activator.CreateInstance(valueType);
var key = Convert.ChangeType(prop.Name,keyType);
dictionaryInstance.Add(key,value);
return(T)dictionaryInstance;


如果(prop.Value!= null)
{
//默认
return(T)Convert.ChangeType(prop.Value, typeof运算(T));
}
}
catch {}
return default(T);

$ / code>

通过这种方式,我可以调用像这样的方法

  //将返回一个类型字典,其中EntityObjectProperty名称为key,EntityObjectProperty值为值
entityObject.LoadProperty< Dictionary< string,int> >(CartonThreshold)

//将返回一个EntityObjectProperty值的字符串
entityObject.LoadProperty< string>(CartonThreshold)

//将返回Int的EntityObjectProperty值
entityObject.LoadProperty< int>(CartonThreshold)


Id like to be able to work with Dictionaries in generic methods. What Im looking for is a way to get the Type from Key and Value of the dictionary sent to the generic extension method LoadProperty.

This is what I've done so far.

I call the method as an extension

entityObject.LoadProperty<Dictionary<string, int>>("CartonThreshold")
//entityObject.LoadProperty<Dictionary<string, double>>("CartonThreshold")

// ... 

public static T LoadProperty<T>(this EntityObject entity, string name) where T : new()
{
    EntityObjectProperty prop = entity.Properties.Single(x => x.Name.Equals(name));

    // If request dictionary
    if (typeof(T).GetInterface(typeof(IDictionary<,>).Name) != null || typeof(T).Name.Contains("IDictionary"))
    {
        var dictionaryInstance = (IDictionary)new T();

        // Just for testing
        var a = dictionaryInstance.Keys.GetType().Name;
        var b = dictionaryInstance.Values.GetType().Name;

        var key = (T) Convert.ChangeType(prop.Name, typeof (T));
        var value = (T) Convert.ChangeType(prop.Value, typeof (T));
        dictionaryInstance.Add(key, value);
        return (T) dictionaryInstance;
    }

    // default
    return (T)Convert.ChangeType(prop.Value, typeof(T));
}

The goal is to return a correctly typed dictionary

解决方案

What I was looking for was the GetGenericArguments() extension of GetType()

The method below will return what I need.

public static T LoadProperty<T>(this EntityObject entity, string name) where T : new()
{
    EntityObjectProperty prop = entity.Properties.Single(x => x.Name.Equals(name));

    try
    {
        // If request dictionary
        if (typeof(T).GetInterface(typeof(IDictionary<,>).Name) != null || typeof(T).Name.Contains("IDictionary"))
        {
            var dictionaryInstance = (IDictionary)new T();

            var typing = dictionaryInstance.GetType().GetGenericArguments();
            Type keyType = typing[0];
            Type valueType = typing[1];

            // dictionary fallback, set to default of the valuetype if null
            object value = prop.Value != null ? Convert.ChangeType(prop.Value, valueType) : Activator.CreateInstance(valueType);
            var key = Convert.ChangeType(prop.Name, keyType);
            dictionaryInstance.Add(key, value);
            return (T)dictionaryInstance;
        }

        if (prop.Value != null)
        {
            // default
            return (T)Convert.ChangeType(prop.Value, typeof(T));
        }
    }
    catch { }
    return default(T);
}

This way I can call the method like this

// Will return a typed dictionary with the EntityObjectProperty name as key and the EntityObjectProperty Value as value
entityObject.LoadProperty<Dictionary<string, int>>("CartonThreshold")

// Will return a string of the EntityObjectProperty Value
entityObject.LoadProperty<string>("CartonThreshold")

// Will return an Int of the EntityObjectProperty Value
entityObject.LoadProperty<int>("CartonThreshold")

这篇关于在泛型方法中从字典获取键和值类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆