简体   繁体   中英

C#, Is it possible to recast an object and access methods and properties without creating new object variable

C#, Is it possible to recast an object and access methods and properties without creating new object variable?

For example:

foreach (object o in collection)
{
    if (o is MyType)
        {
            (MyType)o.MyProperty = x
        }
 }

Currently, I have to re-cast o to another variable of MyType [ex: MyType m = (MyType)o ] in order to access methods or properties of MyType. It seems wasteful, so I'm wondering if I'm missing some mechanic that will allow me to skip the declaration of a new object variable.

You can use Linq:

foreach(MyType t in collection.OfType<MyType>()) {}

You can also use direct casting:

foreach(object o in collection)
{
    if(o is MyType)
    {
        ((MyType)o).MyProperty = x;
    }
}

Alternatively if you you know or want to make sure (keep in mind an InvalidCastException would be possible if the collection is mixed types), you can use the Cast Linq method:

// If your collection is all of the same type
foreach(MyType t in collection.Cast<MyType>()) {}

Your code doesn't work because . has higher precedence than the cast. So you need to add parentheses:

foreach (object o in collection) 
{ 
    if (o is MyType) 
        { 
            ((MyType)o).MyProperty = x; 
        } 
 } 

You need two pairs of parentheses.

((MyType)o).MyProperty = x;

Otherwise the casting is applied to the whole expression.


y = (MyType)o.MyMethod(x);

is the same as

y = (MyType)(o.MyMethod(x));

which is not what you want (it casts the result of MyMethod ). Instead write

y = ((MyType)o).MyMethod(x);

Yes you can cast

foreach(var t in collection.Cast<YourType>())
{
  t.MyProperty = x;
}

Nota : but you must know that boxing or unboxing operation are expensive operation in your memory, when you pass from reference type to value type , or value type to reference type.

In this case you don't have this constraints.

implement an Interface

interface MyInterface
{
 string MyProperty;
}

foreach(object o in collection)
{
MyInterface o= originalObject as MyInterface

if (MyInterface!= null)

  ((MyInterface)o).MyProperty = x;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM