强制转换C#输出参数? [英] Casting C# out parameters?

查看:94
本文介绍了强制转换C#输出参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在C#中抛出param参数?我有:

Is it possible to cast out param arguments in C#? I have:

Dictionary<string,object> dict;  // but I know all values are strings
string key, value;

粗略地说(如果我没有静态类型输入),我想这样做:

Roughly speaking (and if I didn't have static typing) I want to do:

dict.TryGetValue(key, out value);

但是这显然无法编译,因为它无法从'输出字符串'转换为'输出对象'".

but this obviously won't compile because it "cannot convert from 'out string' to 'out object'".

我正在使用的解决方法是:

The workaround I'm using is:

object valueAsObject;
dict.TryGetValue(key, out valueAsObject);
value = (string) valueAsObject;

但这看起来很尴尬.

是否有任何语言功能可以让我在方法调用中抛弃参数,所以对我来说这是一个开关吗?我找不到能帮上忙的语法,而且我似乎也找不到与Google相关的任何东西.

Is there any kind of language feature to let me cast an out param in the method call, so it does this switcheroo for me? I can't figure out any syntax that'll help, and I can't seem to find anything with google.

推荐答案

我不知道这是个好主意,但您可以添加一个通用扩展方法:

I don't know if it is a great idea, but you could add a generic extension method:

    static bool TryGetTypedValue<TKey, TValue, TActual>(
        this IDictionary<TKey, TValue> data,
        TKey key,
        out TActual value) where TActual : TValue
    {
        TValue tmp;
        if (data.TryGetValue(key, out tmp))
        {
            value = (TActual)tmp;
            return true;
        }
        value = default(TActual);
        return false;
    }
    static void Main()
    {
        Dictionary<string,object> dict
            = new Dictionary<string,object>();
        dict.Add("abc","def");
        string key = "abc", value;
        dict.TryGetTypedValue(key, out value);
    }

这篇关于强制转换C#输出参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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