logo
down
shadow

Strange generic method call with explicit generic type behaviour


Strange generic method call with explicit generic type behaviour

By : user2952900
Date : November 19 2020, 03:59 PM
Hope this helps I have a non-generic class with a generic method. Generic type on this method defines output type and can't be inferred from usage so I have to explicitly provide generic type. Sometimes this type is passed on from generic caller's method type parameter, but in one instance I have to explicitly provide it myself. , From what you are saying, including the comment:
code :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <runtime>
    <useLegacyJit enabled="1" />
  </runtime>
</configuration>


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]);
    }
}
Why undefined generic parameter of variable drops explicit generic parameter of it's method's return type?

Why undefined generic parameter of variable drops explicit generic parameter of it's method's return type?


By : Tarak Thakkar
Date : March 29 2020, 07:55 AM
hope this fix your issue
Why undefined generic parameter of variable drops explicit generic parameter of it's method's return type?
code :
public static void test(A<?> i)
Cast unknown object to generic interface of interface (from initially explicit generic type of generic collection type o

Cast unknown object to generic interface of interface (from initially explicit generic type of generic collection type o


By : user4035761
Date : March 29 2020, 07:55 AM
it should still fix some issue If you define your Car class with ICollection instead of List, then works:
code :
public class Car : IHasParts<ICollection>
{
    public ICollection Parts { get; set; }
}
Call generic Method with multiple generic Types without specifying every single generic Type

Call generic Method with multiple generic Types without specifying every single generic Type


By : Giri
Date : March 29 2020, 07:55 AM
I wish this helpful for you In C#, there is no partial type inference: You must either specify all or none of the generic arguments, but the latter only works if the compiler is able to infer all types from context. Return types cannot be infered (except for some special cases such as lambdas), so what you want to do is not possible.
Two workarounds:
code :
class Example<T1>
{
    T1 GenericMethod<T2, T3>(T2 parameter1, T3 parameter2)
class Example
{
    T1 GenericMethod<T1>(object parameter1, object parameter2)
Create instance of class with generic type and call method of same generic type from string name of object at runtime

Create instance of class with generic type and call method of same generic type from string name of object at runtime


By : lukawanjohi
Date : March 29 2020, 07:55 AM
Hope this helps I have a generic class that has a generic method that uses the same type as the type passed when instantiating the object. At runtime, I will only know the name of the object I need to pass in by a string representation of that object name. I've read a few things about using Activator and possibly using dynamic but I can't wrap my head around how I need to make this work. Here's a snippet of what my generic class looks like: , Your wrapper got the following signature:
code :
public class MyClass<T> where T : class, new()
var obj = new T();
public class MyClass<T> where T : class, new()
{ 
        public IList<T> MyMethod(Stream stream)
        {
             var data = new List<T>();

             //this
             var obj = new T();

             return data;
        }
}
var obj = new T();

//get type information
var type = obj.GetType();

//find a public method named "DoStuff"
var method = type.GetMethod("DoStuff");

// It got one argument which is a string.
// .. so invoke instance **obj** with a string argument
method.Invoke(obj, new object[]{"a string argument"});
var type = Type.GetType("Some.Namespace.ClassName");
var obj = Activator.CreateInstance(type);
var type = Type.GetType("Some.Namespace.ClassName, SomeAsseblyName");
var obj = Activator.CreateInstance(type);
var type = Assembly.GetExecutingAssembly()
                   .GetTypes()
                   .FirstOrDefault(x => x.Name == "YourName");
var obj = Activator.CreateInstance(type);
Related Posts Related Posts :
  • How to use Addfields in MongoDB C# Aggregation Pipeline
  • MsTest TestCleanup method not called when an unhandled exception is thrown
  • missing last data when exporting gridview to excel
  • How to add array of objects to List in c#
  • Lambda Expression to order (sort) my list collection
  • Library for displaying music notation
  • How to compare two dictionaries in c# and get the output as True and False after validation
  • specify fields to be serialized with JSON
  • How do you obtain the content of a specific node using XmlDocument in C#?
  • How to ignore the first line in a csv file when you read the csv file in C#
  • c# - Problem calling public void from class
  • How to tell a class which objects it should create? Type vs. object confusion :(
  • Save CheckBox state to xml
  • WIX CAQuietExec NETSH Command Fails
  • Issues sending http put request every 60 seconds to RoR app
  • ConfigurationManager.ConnectionStrings.ConnectionString Issue
  • Real size WPF controls for printing
  • How to cancel properly?
  • C# String multiplication error
  • Using Solrnet and Assigning Attributes with Entity Framework Generated POCOs
  • Regex pattern for single backslash
  • TextBox: insert spaces for credit card number?
  • C# DLL loaded for exe-application is not found when launching similar DLL by rundll32.exe
  • Debug a Windows Service with WCF library
  • Open a file from an external assembly?
  • Servicestack RegistrationFeature Unable to bind request
  • Index was outside the bounds of the array confusion
  • Error in Xml to List code. The ':' character, hexadecimal value 0x3A, cannot be included in a name
  • I am trying to do a while loop with a string conditional statement in C#
  • C# 'Cannot access a disposed object. Object name: 'SslStream'.'
  • How to make Gecko use seperate CookieContainer per instance?
  • C# Advanced form "please wait"
  • Send and Receive data C# using network stream
  • How to discover that appsettings changed in C#?
  • Check what needs full trust
  • What is the execution order of an MVC Razor view/layout
  • Table designer (Entity Framework) is too resource intense
  • How to clean up an exception string so it can be displayed via Javascript Alert?
  • Configuring Amazon SES Feedback Notifications via Amazon SNS in ASP.NET MVC (C#)
  • C# api responce and request
  • Dynamodb putitem function not working properly
  • theme in windows phone(light or dark) using c#
  • Backup attached database file(.mdf) using c# and SQL Server
  • What is 'TextFile' and where it is uses in WPF project
  • Using same alias for multiple namespaces
  • how to move mails into separate folders
  • Multithreaded Uploader
  • Memory fragmentation?
  • C# correct exception handling
  • "Could not open macro storage" when accessing using file on another machine
  • How to access other directories of hosted server
  • C# Jagged Array check if value exists/true
  • Why can't I type Clone() properly?
  • exception on accessing dictionary from list
  • Getting the immediate response from server without waiting to 200 message
  • Why am I getting exception Directory Is Not empty?
  • Could not load file or assembly 'CefSharp.dll' or one of its dependencies
  • Sending Email By Using C# in unity3D?
  • Correct usage of await async in webapi
  • Program update code issue
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org