C#:将字符串转换为对象 [英] C# : Convert string to Object

查看:3163
本文介绍了C#:将字符串转换为对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的所有人,
我想编写一个参数为通用的函数(以便我可以传递字符串或定义的结构之类的ny类型.我像下面那样穿


Dear All,
I want to write a function whose arguments are generic (so that i can pass ny type like string or defined struct. I wore like below


public struct Book
{
    public decimal price;
    public string title;
    public string author;
}


public int GenericFun(                                            Object i_objCondition,
                                            List<Object> io_objListOutValue)
{
// Do some operation
}

int main()
{
    List<string>    Obj1      = null;
            string          s1= ""s1;
            string          s2= "s2";

            Obj1.Add(strLoginName);
            Obj1.Add(strpassword);
            Obj1.Add(strdomain);

    string sCondition = "";
    GenericFun(sCondition, Obj1);

    List<Book> objBook = null;
    Book Book1;
    Book Book2;
    GenericFun(sCondition, objBook);
}



但是我收到错误消息参数2:无法从System.Collections.Generic.List< string>转换为System.Collections.Generic.List< object>



But I'';m getting error "Argument 2: cannot convert from System.Collections.Generic.List<string> to System.Collections.Generic.List<object>

推荐答案

这里讨论了类似的问题
http://stackoverflow. com/questions/6557/in-c-why-cant-a-liststring-object-be-stored-in-a-listobject-variable [ ^ ]

要转换List< string>到List< object>,List< string>的每个元素都是将被强制转换为以下对象类型
A similar problem is discussed here
http://stackoverflow.com/questions/6557/in-c-why-cant-a-liststring-object-be-stored-in-a-listobject-variable[^]

To convert List<string> to List<object>, each element of List<string> is to be cast to object type as below
List<string> Obj1 = new List<string>();
Obj1.Add(strLoginName);
Obj1.Add(strpassword);
Obj1.Add(strdomain);
List<object> Obj1AsObjects = Obj1.Cast<object>().ToList();
string scondition = "";
GenericFun(scondition, Obj1AsObjects);



但是然后在GenericFun 中可以对parameters进行什么操作.因为,对象类型只有基本的方法,对于执行某些实际的计算或其他操作可能没有多大用处.因此,最好使用类和接口创建一个层次结构,然后将参数类型作为该层次结构的基类传递.



But then in GenericFun what operation can be done on the parameters. Because, Object type has only the basic methods, which may not be much useful to perform some practical calculations or other manipulations. Hence, it is preferable create a heirarchy using classes and interfaces and then pass the parameter type as the base class of this heirarchy.


//In GenericFun() method call, use casting as below
GenericFun((Object)sCondition, (List<Object>)objBook);
</string>


使用这些泛型的一种惩罚是装箱/拆箱.我想,您必须转换List< string>列出< object>然后传递给该方法.
您可以尝试使用Obj1.CovertAll(...)方法执行此操作
A penality in using these generics is boxing/unboxing. I guess, you have to convert List<string> to List<object> and then pass on to the method.
You can try using Obj1.CovertAll(...) method for doing this


这篇关于C#:将字符串转换为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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