相关疑难解决方法(0)

函数返回一个泛型类型,其值仅在运行时已知

我需要使用如下通用接口:

public interface IContainer<T>
{
    IEnumerable<IContent<T>> Contents { get; }
}
Run Code Online (Sandbox Code Playgroud)

实现此接口的对象由以下通用方法返回:

IContainer<T> GetContainer<T>(IProperty property);
Run Code Online (Sandbox Code Playgroud)

T在运行时之前,类型是未知的.

使用反射我可以调用GetContainer<T>方法并获得结果.

我的问题是我不知道如何枚举具有类型的结果Object(因此我无法将其强制转换IEnumerable).

我也试过如下铸造,但它不起作用(它说"预期类型"):

var myContainer = genericMethodInfo.Invoke(
                           myService, 
                           new object[] { property })
    as typeof(IContainer<>).MakeGenericType(type);
Run Code Online (Sandbox Code Playgroud)

type运行时类型在哪里,myService是暴露GetContainer<T>方法的服务,并且propertyIProperty根据需要的类型.

更新:在我的博客中查看我的完整解决方案:http://stefanoricciardi.com/2010/02/18/generics-with-type-uknown-at-compile-time/

c# generics reflection

5
推荐指数
0
解决办法
3269
查看次数

如何获得类型

我需要使用如下方法:

DoSomething<(T)>();
Run Code Online (Sandbox Code Playgroud)

但我不知道我有哪种类型,只有类型的对象.如果我只有以下情况,我该如何调用此方法:

Type typeOfGeneric;
Run Code Online (Sandbox Code Playgroud)

c# generics

5
推荐指数
1
解决办法
2万
查看次数

使用System.Type调用泛型方法

我使用的是C#/ .NET 4.0和一个Protocol Buffers库(protobuf-net),它提供了以下功能.

public static class Serializer {
    public static void Serialize<T>(Stream destination, T instance);
    public static void Serialize<T>(SerializationInfo info, T instance);
    public static void Serialize<T>(XmlWriter writer, T instance);
    public static void Serialize<T>(SerializationInfo info, StreamingContext context, T instance);
    public static T Deserialize<T>(Stream source);
}
Run Code Online (Sandbox Code Playgroud)

我需要使用非泛型等价物包装其中两个调用.具体来说,我想要

void SerializeReflection(Stream destination, object instance);
object DeserializeReflection(Stream source, Type type);
Run Code Online (Sandbox Code Playgroud)

它只是Serializer在运行时调用相应的通用成员.我已经得到了DeserializeReflection使用以下代码的方法:

public static object DeserializeReflection(Stream stream, Type type)
{
    return typeof(Serializer)
        .GetMethod("Deserialize")
        .MakeGenericMethod(type)
        .Invoke(null, new object[] { stream …
Run Code Online (Sandbox Code Playgroud)

.net c# generics system.reflection

5
推荐指数
1
解决办法
1754
查看次数

带有Generic重载的Type.GetMethod - 获取Generic MethodInfo而不循环遍历所有方法

我有两个功能:

  1. public void DeleteRecord(int id);
  2. public T DeleteRecord<T>(int id);

以下是我尝试动态调用泛型方法的方法:

MethodInfo method = typeof(DAL).GetMethod("DeleteRecord", new[] { typeof(int) });
MethodInfo generic = method.MakeGenericMethod(returnType);
object o = generic.Invoke(null, new object[] { dbname, spname, expandoAsDictionary });
Run Code Online (Sandbox Code Playgroud)

第一行抛出异常,因为它找到了一个模糊的定义.有没有办法可以获得MethodInfo泛型方法而不使用GetMethods和循环查询结果IsGenericMethod

编辑:请删除'复制',因为两个建议的答案要么用内循环解决这个问题(GetMethods().选择...)或者甚至不解决重载问题.

c# reflection methodinfo

5
推荐指数
1
解决办法
1351
查看次数

我可以使用泛型来推断已知类型的实际类型吗?

我想做的事:使用Activator动态创建一个对象(可以是任何类型)并将其传递给序列化JSON的方法.注意:我已经看过使用泛型扩展方法的无类型推断,但这并没有真正给我任何有关如何解决这个问题的有用信息.

编辑:使用.NET 3.5 Framework

问题:我收到的对象可能是一个数组(例如int []),当我使用泛型来键入接收到的对象时,我得到一个对象[]而不是int [].

代码示例:

class Program
{
    static void Main(string[] args)
    {
        object objArr = new int[0];
        int[] intArr = new int[0];
        string arrS = "[1,2]";

        object objThatIsObjectArray = Serialize(objArr, arrS);//I want this to evaluate as int[]
        object objThatIsIntArray = Serialize(intArr, arrS);//this evaluates as int[]

        Console.Read();
    }
    public static object Serialize<T>(T targetFieldForSerialization, string value)
    {
        return value.FromJson<T>();
    }

}

public static class JSONExtensions
{
    public static TType FromJson<TType>(this string json)
    {
        using (var ms …
Run Code Online (Sandbox Code Playgroud)

c# generics reflection serialization json

5
推荐指数
1
解决办法
594
查看次数

通过实体类名动态获取 DbSet&lt;T&gt;

我正在尝试使用它的名称动态System.Reflections获取DbSet<T>

我现在有的是:

  • DbSet
  • 所述DbSetType存储在可变

在尝试使用该dbcontext.Set<T>()方法时,我面临的问题出现了,因为(这些是我迄今为止的尝试):

  • 当我尝试分配给<T>my 时DbSet Type,它会引发以下编译错误:

    “XXX 是一个变量,但像类型一样使用”

  • 如果我尝试使用两种Extension方法,您将在我的代码下面找到(我为了设法弄一本制作IQueryable<T>),它返回一个IQueryable<object>,不幸的是不是我期待的,因为当然,当我尝试用进一步的反射操作它,它缺少原始类具有的所有属性......

我究竟做错了什么?我怎样才能得到一个DbSet<T>

我的代码如下,当然,如果您需要更多信息、说明或代码片段,请告诉我。

我的控制器的方法

public bool MyMethod (string t, int id, string jsonupdate)
{
    string _tableName = t;
    Type _type = TypeFinder.FindType(_tableName); //returns the correct type

    //FIRST TRY
    //throws error: "_type is a variable but is used like a type"
    var tableSet = _context.Set<_type>();  

    //SECOND …
Run Code Online (Sandbox Code Playgroud)

c# system.reflection entity-framework-core asp.net-core

5
推荐指数
1
解决办法
6939
查看次数

如果我只有Type实例,如何调用泛型方法?

class A
{
    public static void M<T>() { ... }
}

...
Type type = GetSomeType();
Run Code Online (Sandbox Code Playgroud)

然后我需要在A.M<T>()哪里打电话type == typeof(T).
反射?

.net generics

4
推荐指数
1
解决办法
1418
查看次数

反射:作为结果使用通用列表调用方法

我有以下示例类:

public class MyClass<T>
{
    public IList<T> GetAll()
    {
        return null; // of course, something more meaningfull happens here...
    }
}
Run Code Online (Sandbox Code Playgroud)

我想GetAll用反思来调用:

Type myClassType = typeof(MyClass<>);
Type[] typeArgs = { typeof(object) };
Type constructed = myClassType.MakeGenericType(typeArgs);
var myClassInstance = Activator.CreateInstance(constructed);

MethodInfo getAllMethod = myClassType.GetMethod("GetAll", new Type[] {});
object magicValue = getAllMethod.Invoke(myClassInstance, null);
Run Code Online (Sandbox Code Playgroud)

这导致(在上面的代码的最后一行):

无法对ContainsGenericParameters为true的类型或方法执行后期绑定操作.

好的,第二次尝试:

MethodInfo getAllMethod = myClassType.GetMethod("GetAll", new Type[] {});
getAllMethod = getAllMethod.MakeGenericMethod(typeof(object));
object magicValue = getAllMethod.Invoke(myClassInstance, null);
Run Code Online (Sandbox Code Playgroud)

这导致(在上面代码的倒数第二行):

System.Collections.Generic.IList`1 [T] GetAll()不是GenericMethodDefinition.MakeGenericMethod只能在MethodBase.IsGenericMethodDefinition为true的方法上调用.

我在这做错了什么?

c# generics reflection

4
推荐指数
1
解决办法
4002
查看次数

通用方法使用运行时类型执行

这很奇怪,但源代码

public class Processor<T> where T: class
{
...
    private object WorkWithSubtype(IRequester nextRequester, Type type)
    {
        if (type.GetInterface("IList") != null)
        {
            var originalType = type.GetGenericArguments()[0];
            var list = Activator.CreateInstance(type);

            var method = typeof(Processor<>).GetMethod("GetObjects", BindingFlags.NonPublic | BindingFlags.Instance).MakeGenericMethod(originalType);
            var resList = method.Invoke(this, new object[] { nextRequester });
            typeof(List<>).GetMethod("AddRange").MakeGenericMethod(originalType).Invoke(list, new object[] { resList });
            return list;
        }
    }

    private IEnumerable<K> GetObjects<K>(IRequester requester) where K: class
    {
        ...
        //We can call method WorkWithSubtype in this method sometimes
    }
}
Run Code Online (Sandbox Code Playgroud)

我得到"无法对ContainsGenericParameters为真的类型或方法执行后期绑定操作." 例外情况是抛出'var resList = method.Invoke(this,new …

.net c# reflection

4
推荐指数
1
解决办法
748
查看次数

C#将通过反射找到的类型用作泛型

我正在尝试使用Type作为泛型。本质上,我能够使用反射根据其签名找到一个Type。我现在需要执行以下操作:

Type theType = this.getMyType(mySignature);
string convertedData = mappingObj.mapIt<DataBase, theType>(myData);
Run Code Online (Sandbox Code Playgroud)

但是,我不能theType用作泛型。有没有办法做到这一点?

编辑:根据Sohaib Jundi的建议,我遇到了以下问题(非简化代码正在与Automapper的Map方法一起使用):

typeof(IMapper).GetMethod("Map")
Run Code Online (Sandbox Code Playgroud)

该行产生此错误:

'typeof(IMapper).GetMethod("Map")' threw an exception of type 'System.Reflection.AmbiguousMatchException'
Run Code Online (Sandbox Code Playgroud)

我尝试通过GetMethod获取的方法是Map<TDestination, TSource>(TSource source),但是我无法确定要获取该方法而调用的方法签名。作为参考,这是Map方法所在的自动映射器IMapper类的链接。

AutoMapper IMapper

c# generics reflection automapper

4
推荐指数
1
解决办法
92
查看次数