我可以将类型字符串转换为类类型 [英] May I convert type string to a class type

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

问题描述

我做了类似下面的事情:

i did something like below:

string name="something";

var upload = new Upload
            {
                UploadID=1,
                ImageName = name,

            };





这里上传是一个类名,有两个属性,如:



here Upload is a class name which has two property like:

public class Upload
    {
        public int UploadID { get; set; }
        public string ImageName { get; set; }
    }





无法将字符串分配给类类型。那么如何将字符串类型转换为上传类类型???



it's not possible to assign a string to a class type . So how can I convert the string type to the upload class type???

推荐答案

这应该可以正常工作 - 如果你的目标是V3.0或更高版本。 NET框架 - 它不会在下面工作。

MSDN:Object Initializers [ ^ ]

例如,这有效:

That should work fine - if you are targeting V3.0 or above of the .NET framework - it won't work below that.
MSDN: Object Initializers[^]
For example, this works:
class Program
    {
    static void Main(string[] args)
        {
        string name = "something";

        var upload = new Upload
        {
            UploadID = 1,
            ImageName = name,
        };
        Console.ReadLine();
        }
    }
public class Upload
    {
    public int UploadID { get; set; }
    public string ImageName { get; set; }
    }


如果我理解你的话......

这是可能的,但你需要定义类构造函数 [ ^ ]。



If i understand you well...
It's possible, but you need to define class constructor[^].

public class Upload
    {
        //variables
        private int id=0;
        private string simagename = String.Empty;

        //
        public Upload(int iid, string sname){id = iid; simagename = sname;}
        public int UploadID { get; set; }
        public string ImageName { get; set; }
    }





用法:



Usage:

Upload u = new Upload(1, "something");






or

int myid = 1;
string simagename = "Wallpaper.jpg";
Upload u = new Upload(myid, simagename);


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

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