【问题标题】:C# string to var objectC# 字符串到 var 对象
【发布时间】:2017-05-24 11:03:40
【问题描述】:

我有一个字符串“hello”和一个整数 1。

我想把它们转换成

new { hello= 1 } 

动态地,并且不使用像

这样的任何条件
switch(p1){
case "hello":
return new {hello=p2};
}

因为有许多不同的字符串,我需要将许多项目放入一个超级对象集中,例如

var emotion = {smile=1,angry=2,worry=3}

问题是微笑,生气和担心是字符串。但是加上情感之后,它们不是字符串,而只是一个索引(就像字典一样,但是字典的索引也有dataType,这不是我的预期结果)

有可能吗?

--- 更新 --- 我添加了一个函数来指定预期的输出。

private void Question_1()
{
    //i have
    string a = "hello";
    int b = 1;
    // i want to convert a and b to new {a = b} programmatically, for example i can convert a and b to a Tuple like
    Tuple<string, int> x = new Tuple<string, int>(a,b);
    //but i dont know how to to convert it to new {a = b}, as i need to put the string "hello" as key to new {a=b}
    var result = new { hello = b }; //you can see i can put b after =, but i can never put the string hello at the left
}
private void Question_2()
{
    //and the final should be like this
    List<Tuple<string, int>> list = new List<Tuple<string, int>>() {
        new Tuple<string,int>("smile",1),
        new Tuple<string,int>("cry",2),
        new Tuple<string,int>("worry",3)
    };
    foreach (Tuple<string, int> item in list)
    {
        //adding item's string and int into result and finally the result is
    }
    //the final result
    var finalResult = new { smile = 1, cry = 2, worry = 3 };
}

【问题讨论】:

  • 你可以使用enum
  • 如果文本和值是动态的,你可以试试字典。
  • 输入字符串是随机的,因此它会是一个非常大的枚举,我认为它不起作用...
  • 重点是我不想硬编码任何东西(例如枚举)来转换对象。谢谢
  • 听起来很像这个问题:stackoverflow.com/questions/4938397/…

标签: c# asp.net-mvc


【解决方案1】:

对枚举使用 .NET 命名约定:它们应该是 Pascal 表示法。

enum Emotion
{
    Smile = 1, Angry = 2, Worry = 3
}

var l = new List<Emotion> { Emotion.Angry, Emotion.Smile, Emotion.Worry };

您还可以使用 DesriptionAttribute 为枚举使用友好名称,如下所示:

enum Emotion
{
    [Description("Smiling")]
    Smile = 1,
    [Description("Angry Type")]
    Angry = 2,
    [Description("Worry Type")]
    Worry = 3
}

【讨论】:

    【解决方案2】:

    你有什么理由不能只使用字典?

    var hi = new Dictionary<string,int>();
    hi[p1] = p2;
    return hi; // Would serialize the same way as your anonymous object
    

    如果没有,那么您可以使用 expando 对象在运行时动态设置属性。

    var hi = new ExpandoObject() as IDictionary<string, object>;
    hi.Add(p1, p2);
    var p2Value = (int)((dynamic)hi).hello;
    

    【讨论】:

    • hi 字典实际上不起作用,因为它是 ,我想要的是 new{ hello=1},请注意 hello 实际上不是输出中的字符串。目的是将一个字符串和一个int(实际上它不仅仅是int,因为它也可以是其他类型)转换为> new {stringValue:intValue},只是为了强调stringValue实际上不是字符串,它类似于那个东西的索引(我真的不知道我是否应该称它为数组)
    • Dictionary 是一个通用对象...您可以将其定义为任何您喜欢的 ,任何符合您要求的东西。如果您将其作为 Web API 或 MVC 操作的一部分返回,那么 JSON 的序列化应该非常相似(如果不相同)。
    • 是的,但我不知道这个对象中 hello 的数据类型是什么 ==> new {hello=1} ,如何实现输入为字符串和整数的字典,以及输出是: var output = new {stringVal=intValue} .
    • 猜我错过了什么。似乎“hello”要么是字符串,要么必须转换为字符串才能成为匿名对象的键值。在任何一种情况下,我都不明白为什么这些技术都不能工作(因为可以将“p2”值转换为 int、string、object 或任何您想要的数据类型。
    【解决方案3】:

    您可以使用 ExpandoObject。

    class Program
        {
            static dynamic obj = new ExpandoObject();
            static void Main(string[] args)
            {
                AddProperty("City", "Sydney");
                AddProperty("Country", "Australia");
                AddProperty("hello", 1);
    
                Console.WriteLine(obj.City);
                Console.WriteLine(obj.Country);
                Console.WriteLine(obj.hello);
    
                //We can even use dynamic property names ( e.g. cityProp in below example ) 
                IDictionary<string, object> dic = obj as IDictionary<string, object>;
                Console.WriteLine("City is : " + dic[cityProp]);
            }
    
            public static void AddProperty(string propertyName, object value)
            {
                IDictionary<string, object> a = obj as IDictionary<string, object>;
                a[propertyName] = value;
            }
        }
    

    【讨论】:

    • 它不起作用,我需要它能够被 Url.Action("action","controller", x) 接受,其中 x 是我试图动态创建的东西。我不知道是动态太复杂还是什么。但是 Url.Action 不知道如何阅读它
    【解决方案4】:
    dynamic emotion = new { smile = 1, angry = 2, worry = 3 };
    Console.WriteLine(emotion.smile);
    

    像这样?

    编辑:根据您对另一个答案的评论:

    它不起作用,我需要它能够被接受 Url.Action("action","controller", x),其中 x 是我正在尝试的东西 动态创建。我不知道是动态太复杂还是什么。 但是 Url.Action 不知道如何阅读它

    这个问题显然不仅仅是 C#,显然这是一个 MVC 问题。你真的应该尽可能多地添加关于你需要什么的信息。

    你的答案大概就在这里:

    https://stackoverflow.com/a/15112223/1685167

    @Url.Action() 方法是在服务器端处理的,所以你不能 将客户端值作为参数传递给此函数。

    【讨论】:

    • 不是真的,假设我有“微笑”、“愤怒”、“担心”和 1、2、3。我需要实现一个程序来动态转换它们的情感
    • 我不确定您为什么认为我将客户端值传递给 Url.Action。 new { para=1,para2=2,para3=3} 是一个常规的服务器端对象。我可以手动实现它并将其放入 Url.Action 没有任何问题。我的问题是为 Url.Action 创建新的 { para=1,para2=2,para3=3}。而且我认为创建 new { para=1,para2=2,para3=3} 是 C#(将一组字符串和 int 转换为该对象)
    • @SKLTFZ 首先很好,因为您 need it able to be accepted by Url.Action("action","controller", x) 您应该相应地添加适当的标签和更多信息。其次,“new { para=1,para2=2,para3=3}”不是“将一组字符串和 int 转换为该对象”。它们只是对象中的变量名和值。这就是使您所说的话令人难以置信的混乱的原因。而且由于您拒绝回答您的问题的所有其他答案,这可能是因为您缺乏信息。
    • 目标是通过 url.action 接受。但通常您仍然可以在调试期间检查输出。上面提供的答案不能与 new{p1=1,p2=2,p3=3} 相同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-10
    相关资源
    最近更新 更多