Using a reference to a shared object as a parameter

I am having some problems passing a reference to an object that has a common type. I found a way by creating an “Object” and passing a link to it, not the original, but it seems to me that it smells a bit. Is there a better way here or do I need to live with it?

I understand the first mistake, but the second eludes me.

public static T Foo<T>(ref T Bar)
{
    T Result;

    // Next line gives
    // cannot convert from 'ref T' to 'ref object'
    Result = (T)ModifyObject (ref Bar);

    // Next line gives
    // A ref or out argument must be an assignable variable
    Result = (T)ModifyObject (ref ((Object)Bar) );

    // Works
    Object Tmp = Bar;
    Result = (T)ModifyObject (ref Tmp) );

    return Result;

}

public static Object DoSomthing(ref Object Obj) {
    Object Result = Activator.CreateInstance (Obj.GetType ())
    //...
}

DoSomething is not generic because it uses recursion where the type of Obj can change. I tried to distract from the use of reflection to name its general version, although perhaps this would be better for publication.

+3
source share
3 answers

ref . . : ref out ?

+5

:

ref out

: : (Object) bar , . , , . , - . , rvalues: .

: , lvalue, (, ).

+3

:

object obj = (object)Bar;
Result = (T)ModifyObject (ref obj);

, , , , obj Object. .

And the code smells a bit. If you return a result of type T, then I see no reason to pass the parameter by reference. Secondly, you do not need to pass an instance of your type by reference in order to create it. This method will work very well:

public static Object DoSomething(Type objType) {
    Object Result = Activator.CreateInstance(objType)
}

And finally, if you use generics, then there should be no reason to do all the casting. This is why a generic parameter is used to make your class a template for different types.

0
source

Source: https://habr.com/ru/post/1719954/


All Articles