从父类中赋值。简单的

发布于 2024-08-24 01:47:50 字数 480 浏览 6 评论 0原文

怎么做类似的事情:

Class Car: string Name, int year
Class SUV:Car;

SUV bmw=ToCar(car);

类似的事情?

public object ToObject(Type type, Car car)
{
// here i just wanna take string and int pool
}

我做了类似的事情:

List<Car> cars=new List<Car>

SUV suv=new SUV();

cars.Add(suv).

接下来我想要:

SUV suv=(Suv)cars[0];

但我收到一个错误,表明此转换是错误的。 :/

我只想恢复 SUV。

How do something like that:

Class Car: string Name, int year
Class SUV:Car;

SUV bmw=ToCar(car);

Something like that ??

public object ToObject(Type type, Car car)
{
// here i just wanna take string and int pool
}

I did something like:

List<Car> cars=new List<Car>

SUV suv=new SUV();

cars.Add(suv).

And next I want:

SUV suv=(Suv)cars[0];

But I get an error that this casting is wrong. :/

I want to just recover the SUV.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

戒ㄋ 2024-08-31 01:47:50

看起来您已经有了基本的想法,您的示例中存在一些命名错误,我假设这些错误只是拼写错误,而不是实际代码的样子...这样的东西工作正常,这就是您的样子正在达到:

static void Main(string[] args)
        {
            List<Car> cars = new List<Car>();
            SUV suv = new SUV { name = "mySuv", year = 2010 };
            cars.Add(suv);

            SUV anotherSuvReference = (SUV)cars[0];
            Console.WriteLine(anotherSuvReference.name);
        }

        class Car
        {
            public string name;
            public int year;
        }
        class SUV : Car
        {
        }

It looks like you've got the basic idea, there were some naming errors in your example that I'm assuming were just typos and not what the actual code looks like...something like this works fine which is what it looks like you are getting at:

static void Main(string[] args)
        {
            List<Car> cars = new List<Car>();
            SUV suv = new SUV { name = "mySuv", year = 2010 };
            cars.Add(suv);

            SUV anotherSuvReference = (SUV)cars[0];
            Console.WriteLine(anotherSuvReference.name);
        }

        class Car
        {
            public string name;
            public int year;
        }
        class SUV : Car
        {
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文