无法在WPF中操作实例化对象

时间:2015-02-13 19:28:19

标签: c# wpf oop

好的我是c#的新手,我熟悉WPF + VB.NET。 所以我有一个名为'Voiture'的课程 如果我尝试在MainWindow.cs中实例化一个'Voiture'类型的对象, 我可以做到这一点,但每当我尝试调用该对象使用其中一个方法时,IDE就没有引用它,即使它允许我实例化它 我在这里错过了什么吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfApplication13
{
    class Test
    {
        Voiture b = new Voiture();
        b.speed();

    }
}

如果我尝试b.speed()例如(速度是类Voiture的方法)我得到错误:无法解析符号

2 个答案:

答案 0 :(得分:1)

此代码在结构上无效:

class Test
{
    Voiture b = new Voiture();
    b.speed();
}

您不能在方法或函数的上下文之外强制调用代码。声明变量b的第一行很好,因为它声明性地创建了一个类级别的值。但是不能执行代码语句。只有方法或功能才能。像这样:

class Test
{
    Voiture b = new Voiture();

    public void SomeMethod()
    {
        b.speed();
    }
}

答案 1 :(得分:0)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfApplication13
{
    class Test
    {
        Voiture b = new Voiture();
        b.speed(); // this is wrong

    }
}

这是用途。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfApplication13
{
    class Test
    {
        Voiture b = new Voiture();            

        public Test() // constructor
        { 
            b.speed();
         }

        public void function() // function
        { 
            b.speed();
        }
    }
}
相关问题