C # General method and dynamic type problem

I have a generic method declared as follows:

public void Duplicate<EntityType>() { ... }

So, as a rule, I just have to say:

myObject.Duplicate<int>()

But here I would like to pass the type of the variable, but this will not work, here is how I try to do it:

Type myType = anObject.GetType();
myObject.Duplicate<myType>();

If anyone can help me?

Thanks in advance.

+3
source share
4 answers

You should use reflection, mainly:

MethodInfo method = typeof(...).GetMethod("Duplicate");
MethodInfo generic = method.MakeGenericMethod(myType);
generic.Invoke(myObject, null);
+12
source

If you have a type as a variable, you really don't have a good candidate for generic methods, especially since your method returns nothing.

You would be better off:

public void Duplicate(Type entityType) { ... }

Then your code will look like this:

Type myType = anObject.GetType();
myObject.Duplicate(myType);

Jon Skeet (), , , , .

- box/unbox ..

( a void) . , . , - , , - :

public void Duplicate<EntityType>() 
{
 ...
 Type inputType = typeof(EntityType); 
 ...
}

EntityType, , , , .

+4

, Type :

myobject.Duplicate(myType);

, - :

System.Reflection.MethodInfo mi = typeof(TypeOfMyObject).GetMethod("Duplicate<>");
MethodInfo constructedMethodInfo = mi.MakeGenericMethod(new type[] {myType});
constructedMethodInfo.Invoke(myObject, new object[] {});
0

Duplicate(), , , Duplicate(), int.

, , . ( )

    [TestMethod]
    public void TestMethod1()
    {
        var myObject = new AnObject { AString = "someString" };

        var myOtherObject = new AnotherObject();
        var newObject = myObject.Duplicate(myOtherObject);
        Assert.IsTrue(newObject.AString=="someString");

        var newObject2 = myObject.Duplicate(1);
        Assert.IsTrue(newObject2 is Int32);
    }

Duplicate() , -, , , -.

Duplicate():

public class AnObject
{
    public string AString { get; set; }

    public T Duplicate<T>(T exampleObject)
        where T: new()
    {
        var newInstance = (T)Activator.CreateInstance<T>();

        // do some stuff here to newInstance based on this AnObject
        if (typeof (T) == typeof (AnotherObject))
        {
            var another = newInstance as AnotherObject;
            if(another!=null)
                another.AString = this.AString;
        }

        return newInstance;
    }
}

, AnotherObject.

public class AnotherObject
{
    public string AString { get; set; }
}

Duplicate(), , , , int. , , Duplicate() int (, , nullable int).

It works well for reference types (classes).

0
source

All Articles