문제

what is difference between these codes?

public class MyClass
{
    object myObject;

    public MyClass()
    {
        myObject = new Label();
        (myObject as Label).Width = 100;
    }
} 

And:

 public class MyClass
    {
        object myObject;

        public MyClass()
        {
            myObject = new object();
            (myObject as Label).Width = 100;
        }
    }

in both of them cast is needed and no error happens.

도움이 되었습니까?

해결책

No compile time error happens. At runtime in the second code block, you'll get the exception that an object really isn't a Label and can't be cast as such.

Because every .NET type inherits from object, you can assign any type to your object myObject; field. In your first code block, a Label instance is assigned to it. You can cast it back to a label as happens at (myObject as Label), because you actually stored a Label in it.

Your second code example stores an object, which isn't a Label, so it can't be cast.

다른 팁

Here's my code to cast an object as label that i've discored while searching for the same solution:

    private void modeloUserControl_Click(object sender, EventArgs e)
    {

        Label label = (Label)sender;
        MessageBox.Show(label.Text);
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top