C# Convert interfaces
Cast a class to an interface is the same as convert a Class to another Class in C#?Does box or unboxing occurs in this process?
interface Area
{
string TxtArea
{
get;
set;
}
}
Convert to it interface:
public void Test()
{
ExternAre开发者_开发技巧a extArea = new ExternArea();
if(extArea is Area)
{
((Area)extArea).TxtArea = "voila";
}
}
Assuming ExternArea
is a class rather than a value type (struct or enum), there's no boxing involved. Boxing only ever converts a value type to a reference type instance.
Note that using as
is generally preferred though:
Area area = extArea as Area;
if (area != null)
{
area.TxtArea = "voila";
}
Boxing only occurs if you convert a value type (a struct or a number) to a reference type (object
or an interface implemented by the struct
)
Casting a reference type (an instance of a class) to a different reference type (a base class or an interface implemented by the class) does not involve boxing.
Even so, you should not cast unnecessarily; instead, use the as
keyword, like this:
Area area = extArea as Area;
if (area != null)
{
area.TxtArea = "voila";
}
Boxing and unboxing have to do with packaging a value type inside an object, so it can be used as a reference type (allocated on the heap). When you're unboxing, you're getting such a value back from the "box". So no, this would not occur in this example.
As long as the ExternArea
object in your code sample is a reference type, then - no - no boxing operations will be performed. Boxing and unboxing refers to operations undertaken when value types are converted into objects.
For more information, please see Boxing and Unboxing (C# Programming Guide).
精彩评论