我需要使用如下通用接口:
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>方法的服务,并且property是IProperty根据需要的类型.
更新:在我的博客中查看我的完整解决方案:http://stefanoricciardi.com/2010/02/18/generics-with-type-uknown-at-compile-time/
我需要使用如下方法:
DoSomething<(T)>();
Run Code Online (Sandbox Code Playgroud)
但我不知道我有哪种类型,只有类型的对象.如果我只有以下情况,我该如何调用此方法:
Type typeOfGeneric;
Run Code Online (Sandbox Code Playgroud) 我使用的是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) 我有两个功能:
public void DeleteRecord(int id);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().选择...)或者甚至不解决重载问题.
我想做的事:使用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) 我正在尝试使用它的名称动态System.Reflections获取DbSet<T>。
我现在有的是:
DbSet名DbSet的Type存储在可变在尝试使用该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) class A
{
public static void M<T>() { ... }
}
...
Type type = GetSomeType();
Run Code Online (Sandbox Code Playgroud)
然后我需要在A.M<T>()哪里打电话type == typeof(T).
反射?
我有以下示例类:
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的方法上调用.
我在这做错了什么?
这很奇怪,但源代码
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 …
我正在尝试使用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类的链接。