logo
down
shadow

Passing Type to Method for Use in Generic


Passing Type to Method for Use in Generic

By : TechTitans
Date : October 28 2020, 08:00 PM
To fix the issue you can do I'm trying to understand why the following code does not work and how I need to change it to make it work. In short, I'm trying to pass a Type into the method and then use that Type when declaring List. , That would be:
code :
public void TestMethod<T>()
{
    List<T> items = new List<T>();
}


Share : facebook icon twitter icon
Given a constrained generic method can I call a non-generic method passing the actual type of the generic parameter

Given a constrained generic method can I call a non-generic method passing the actual type of the generic parameter


By : user2957587
Date : March 29 2020, 07:55 AM
help you fix your problem As Aliostad said, what your trying to do is no longer generic and it would be better to just use overloads. It looks like you are trying to do something similar to template specialization in C++, where depending on the generic type it calls different methods.
Here is an example where I implemented a sort of generic specialization using reflection, you might be able to apply a similar pattern if overloading method wont work for you. If you can cache the results of reflection and only call GetMethod once then it turns out to be not too slow. Inside a class generic by T there is a method that calls:
code :
if (_serializeDataToStream == null)
    _serializeDataToStream = (Action<BinaryWriter, int, T[]>)GetTypeSpecificSerializationMethod();

_serializeDataToStream(writer, _size, _data);
/// <summary>
/// Returns a delegate that points at the static type specific serialization method
/// </summary>
/// <returns></returns>
private Delegate GetTypeSpecificDeserializationMethod()
{
    if (typeof(T) == typeof(double))
    {
        MethodInfo method = this.GetType().GetMethod("DeserializeDouble", BindingFlags.Static | BindingFlags.NonPublic);
        return Delegate.CreateDelegate(typeof(Action<BinaryReader, int, T[]>), method);
    }
    else if (typeof(T) == typeof(ushort))
    {
        MethodInfo method = this.GetType().GetMethod("DeserializeUshort", BindingFlags.Static | BindingFlags.NonPublic);
        return Delegate.CreateDelegate(typeof(Action<BinaryReader, int, T[]>), method);
    }
    else if (typeof(T) == typeof(DateTime))
    {
        MethodInfo method = this.GetType().GetMethod("DeserializeDateTime", BindingFlags.Static | BindingFlags.NonPublic);
        return Delegate.CreateDelegate(typeof(Action<BinaryReader, int, T[]>), method);
    }
    else if (typeof(T) == typeof(bool))
    {
        MethodInfo method = this.GetType().GetMethod("DeserializeBool", BindingFlags.Static | BindingFlags.NonPublic);
        return Delegate.CreateDelegate(typeof(Action<BinaryReader, int, T[]>), method);
    }

    throw new NotImplementedException("No deserialization method has been setup for type " + typeof(T).FullName);
}

/// <summary>
/// Serialize double[] to BinaryWriter
/// </summary>
/// <param name="writer"></param>
/// <param name="size"></param>
/// <param name="data"></param>
private static void SerializeDouble(BinaryWriter writer, int size, double[] data)
{
    for (int i = 0; i < size; i++)
    {
        writer.Write(data[i]);
    }
}
I'm losing the type of a variable in a generic method when passing to a second generic method with varargs

I'm losing the type of a variable in a generic method when passing to a second generic method with varargs


By : Deepchand Prajapati
Date : March 29 2020, 07:55 AM
it should still fix some issue Varargs are syntactic sugar that translates to an array of the given type by the compiler. That means that a method(Type arg...) will become method(Type[] arg).
In Java, you cannot create arrays of Non-reifiable types (types whose type information is lost by erasure). Therefore, a generic varargs such as printClassVarargs(T ... str) will translate to printClassVarargs(Object[] str), effectively resulting in erasure of the type info. This is what you are observing in your test.
code :
public Test();
  Code:
   0:   aload_0
   1:   invokespecial   #8; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   ldc #16; //String 5318008
   2:   astore_1
   3:   aload_1
   4:   invokestatic    #18; //Method printClass:(Ljava/lang/Object;)V
   7:   aload_1
   8:   invokestatic    #22; //Method callPrintClass:(Ljava/lang/Object;)V
   11:  iconst_1
   12:  anewarray   #25; //class java/lang/String
   15:  dup
   16:  iconst_0
   17:  aload_1
   18:  aastore
   19:  invokestatic    #27; //Method printClassVarargs:([Ljava/lang/Object;)V
   22:  aload_1
   23:  invokestatic    #31; //Method callPrintClassVarargs:(Ljava/lang/Object;)V
   26:  return

public static void printClass(java.lang.Object);
  Code:
   0:   getstatic   #40; //Field java/lang/System.out:Ljava/io/PrintStream;
   3:   aload_0
   4:   invokevirtual   #46; //Method java/lang/Object.getClass:()Ljava/lang/Class;
   7:   invokevirtual   #50; //Method java/io/PrintStream.println:(Ljava/lang/Object;)V
   10:  return

public static void printClassVarargs(java.lang.Object[]);
  Code:
   0:   getstatic   #40; //Field java/lang/System.out:Ljava/io/PrintStream;
   3:   aload_0
   4:   invokevirtual   #46; //Method java/lang/Object.getClass:()Ljava/lang/Class;
   7:   invokevirtual   #59; //Method java/lang/Class.getComponentType:()Ljava/lang/Class;
   10:  invokevirtual   #50; //Method java/io/PrintStream.println:(Ljava/lang/Object;)V
   13:  return

public static void callPrintClass(java.lang.Object);
  Code:
   0:   aload_0
   1:   invokestatic    #18; //Method printClass:(Ljava/lang/Object;)V
   4:   return

public static void callPrintClassVarargs(java.lang.Object);
  Code:
   0:   iconst_1
   1:   anewarray   #3; //class java/lang/Object
   4:   dup
   5:   iconst_0
   6:   aload_0
   7:   aastore
   8:   invokestatic    #27; //Method printClassVarargs:([Ljava/lang/Object;)V
   11:  return

}
return generic IEnumerable when passing concrete type parameter for a generic method

return generic IEnumerable when passing concrete type parameter for a generic method


By : Emmanuel Chukwuma Mb
Date : March 29 2020, 07:55 AM
seems to work fine You cannot convert the Type class to a generic T parameter without using reflection. The parameter also needs to be present as part of the method.
Jon Skeet was using type inference by example combined with generics in order to guarantee type safety and simplify the generic code. Unfortunately you will lose that type safety using Type and reflection.
code :
private IEnumerable<EntityObject> GetFilteredData(Type entityType,
                                                  SortedList<string, string> filterList,
                                                  List<int> weeks)
{
    var method = typeof(<class>).GetMethod("GetFilteredDataImpl");
    var generic = method.MakeGenericMethod(entityType);
    return (IEnumerable<EntityObject>)generic.Invoke(this, new[] { filterList, weeks });
}

private IEnumerable<T> GetFilteredDataImpl<T>(SortedList<string, string> filterList,
                                              List<int> weeks)
    where T : EntityObject
{
    var data = _modelContext.CreateObjectSet<T>().AsExpandable();
      // do more filtering and then call .ToList() to return a List<T>
}
private IEnumerable<EntityObject> GetFilteredData(Type entityType, SortedList<string, string> filterList, List<int> weeks)
{
    var instance = (EntityObject)Activator.CreateInstance(entityType);
    return GetFilteredDataImpl((dynamic)instance, filterList, weeks);
}

private IEnumerable<T> GetFilteredDataImpl<T>(T entityType, SortedList<string, string> filterList, List<int> weeks) where T : EntityObject
{
    var data = _modelContext.CreateObjectSet<T>().AsExpandable();
      // do more filtering and then call .ToList() to return a List<T>
}
Generic Method Won't Recognise Generic Type When Passing It as a Parameter

Generic Method Won't Recognise Generic Type When Passing It as a Parameter


By : user2203441
Date : March 29 2020, 07:55 AM
Hope this helps That is because you imported a wrong Fragment in your class that it is not compatible with the fragment argument of the add method.
since you used a getFragmentManager() that means you need to use the non support library for the fragment to enable the generic to be compatible with the add method.
code :
import android.app.Fragment;
Passing an instance of a dynamic type to a generic method in a generic class

Passing an instance of a dynamic type to a generic method in a generic class


By : Haganta Brema Bangun
Date : March 29 2020, 07:55 AM
like below fixes the issue I have a generic class that exposes a generic method. This method receives an instance of the generic object as parameter and modifies this instance. , To answer your question:
code :
var type = typeof(abc);
object instanceToModify = new abc();

var typeToCreate = typeof(GenericClass<>).MakeGenericType(type);
var methodToCall = typeToCreate.GetMethod("GenericMethod");

var genericClassInstance = Activator.CreateInstance(typeToCreate);
methodToCall.Invoke(genericClassInstance, new[] { instanceToModify });
public object GenericMethod(object obj)
{
    // modify the object in some (arbitrary) way
    IEnumerable<FieldInfo> fields = obj.GetType().GetRuntimeFields();
    foreach (var field in fields)
    {
        if (field.FieldType == typeof(string))
        {
            field.SetValue(obj, "This field's string value was modified");
        }
    }

    return obj;
}
Related Posts Related Posts :
  • How to use Selenium Grid with C#?
  • What is the best way to download files via HTTP using .NET?
  • How to get files from a device using USB
  • Given a user's SID, how do I get their userPrincipalName?
  • NHibernate mapping in Asp.Net using MySql
  • Why do some cookies have a '.' before the domain?
  • C# SqlDataReader = null?
  • InvalidCastException for two Objects of the same type
  • "The parameters dictionary contains a null entry for parameter" - How to fix?
  • Font family name from font file
  • What is the best way to generate KML files in C#?
  • How can I receive mail using .NET?
  • How to send raw data over a network?
  • meaning of '+='
  • Object reference not set to an instance of an object #5
  • C# Create "wireframe"/3D "map"
  • How to change size of database
  • Serialization problem
  • Using unmanaged code from managed code
  • Are there any bindings between .NET and TK
  • error with linq join
  • VB.NET equivalent to C# var keyword
  • Accessing object properties from string representations
  • Inheritance issue
  • C# timer won't tick
  • How to retrieve items from a database c#
  • Sending mail using SmtpClient in .net
  • Tag problem c# listbox
  • How to know if the Form App open or not c#
  • C# XPath id() not working?
  • Load PDF from Memory ASP.Net
  • C# ListView with a ProgressBar
  • Getting the right WPF dispatcher in a thread
  • How to create Pivot table using C#?
  • how to download a file from remote server using asp.net
  • Binding files in C#?
  • Copy one object to another
  • How to post on Google Buzz?
  • Generic <T> how cast?
  • Set global hotkeys using C#
  • Change the key being pressed with C#
  • Uploading Large Files
  • How do I get the duration of a video file using C#?
  • how to create instance for a generic type in c#
  • Drag and drop rectangle in C#
  • RSA Encryption C#
  • Title=
  • What is meant by Web Services?
  • The provided URI scheme 'https' is invalid; expected 'http'. Parameter name: via
  • Check if server exists
  • time interval in c#
  • Extracting a sub-string in C#
  • C# - Programmatically Log-off and Log-on a user
  • c# array vs generic list
  • TCPClient in C# (Error)
  • How can I know if a file has been changed in .NET C#?
  • New to C# and trying to use a global variable
  • Convert RGB color to CMYK?
  • Tesseract.NET in C#
  • Is it possible to Update Sharepoint List Without "ID"?
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk