开发者

What do 2 brackets in a row mean in xaml.cs?

开发者 https://www.devze.com 2023-01-16 00:48 出处:网络
Just started learning C# (in xaml), so appreciate some elaboration: ((MSAvalon.Windows.Serialization.ILoaded)(_Text_2_)).DeferLoad();

Just started learning C# (in xaml), so appreciate some elaboration:

((MSAvalon.Windows.Serialization.ILoaded)(_Text_2_)).DeferLoad();

Not sure what all the round brackets means... does it mean "_Text_2_" is a child of object "MSAvalon.Windows.Serialization.ILoaded" ?

and i开发者_高级运维f so... why not just something like:

MSAvalon.Windows.Serialization.ILoaded._Text_2.DeferLoad();


_Text_2_ is casted to a MSAvalon.Windows.Serialization.ILoaded Object/Interface and then the method DeferLoad is called


This is a typecast, used to tell the compiler that a variable is of a particular type when it's not obvious. It could have been used like this:

class Foo {
    private object _Text_2_;

    void Method() {
        ((MSAvalon.Windows.Serialization.ILoaded)_Text_2_).DeferLoad();
    }
}

Leaving out the typecast here would cause a compiler error, since DeferLoad is not a method of object. You're telling the compiler here that you have some special knowledge that _Text_2_ is really what you say it is.


Basically it's started with (( so that DeferLoad can be called. I'll illustrate with an example.

Lets say you do the following.

object s = "Hello world";

s now contains a string. If you want to make this string uppercase using a cast (as in your example, I can't simply write this

(string)s.ToUpper();

ToUpper() can't be called, since it's not valid on a variable of type object. If you rewrite this to

((string)s).ToUpper()

it's valid. Because of the brackets, s is casted to a string first, then string.ToUpper() is called on the variable.

Note that in this case (s as string).ToUpper() would be a cleaner approach.

0

精彩评论

暂无评论...
验证码 换一张
取 消