在C#3.0的命名/可选参数? [英] Named/Optional parameters in C# 3.0?

查看:112
本文介绍了在C#3.0的命名/可选参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法来添加可选参数C#3.0一样会出现在C#4.0吗? !我得有​​这个功能,我都等不及了。

Is there a way to add optional parameters to C# 3.0 like there will be in C# 4.0? I gotta have this feature, I just can't wait!

编辑:

如果你知道,身边工作/破解做到这一点,它张贴也。 !谢谢

If you know a work-around/hack to accomplish this, post it also. Thanks!

推荐答案

您可以使用匿名类型和反思作为一种变通方法来命名的参数:

You can use an anonymous type and reflection as a workaround to named parameters:

public void Foo<T>(T parameters)
{
    var dict = typeof(T).GetProperties()
        .ToDictionary(p => p.Name, 
            p => p.GetValue(parameters, null));

    if (dict.ContainsKey("Message"))
    {
        Console.WriteLine(dict["Message"]);
    }
}



所以,现在我可以调用美孚这样的:

So now I can call Foo like this:

Foo(new { Message = "Hello World" });



...,它会写我的消息。

... and it will write my message.

基本上我提取从传递的匿名类型的所有属性,并将它们转换为字符串和object(属性和它的值的名称)的字典。

Basically I'm extracting all the properties from the anonymous type that was passed, and converting them into a dictionary of string and object (the name of the property and its value).

这篇关于在C#3.0的命名/可选参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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