如何获得提供给闭合/构造的泛型方法的参数值?
我已经有一段时间没有触及反射.所有这些都曾经在我的后面,嗯,无论如何.
class Program
{
static void Main(string[] args)
{
new ConcreteFoo().GenericMethod<int>(5);
Console.ReadKey();
}
}
class ConcreteFoo
{
public void GenericMethod<Q>(Q q)
{
var method = MethodInfo.GetCurrentMethod();
var parameters = method.GetParameters();
if (parameters.Length > 0)
foreach (var p in parameters)
Console.WriteLine("Type: {0}", p.ParameterType);
// That still prints Q as the type.
// I've tried GetGenericArguments as well. No luck.
// I want to know:
// 1) The closed type, i.e. the actual generic argument supplied by the caller; and
// …Run Code Online (Sandbox Code Playgroud) 这是我的第一篇文章,尽管我在某种程度上搜索了与我的问题相关的主题,但我在找到正确的答案时遇到了很多麻烦.
我的问题可能很简单,但我知道答案可能不那么容易.如果存在的话.
话虽如此,这是我的情况:作为一个例子,我有一个PropertyInfo对象数组,我用它来从类中获取属性,如下所示:
public PropertyInfo[] GetProperties (object o)
{
PropertyInfo[] properties = o.GetType().GetProperties();
return properties;
}
Run Code Online (Sandbox Code Playgroud)
看起来很简单吧?现在我的问题是:如何创建一个新的PropertyInfo对象并将其添加到数组?
我看过其他帖子,用户想要设置PropertyInfo的VALUE,但这不是我需要的.我需要的是动态创建一个新的PropertyInfo对象,其中我唯一可用的数据是Name和Type.
我之前发布的测试用例只是我想要实现的一个小例子.事实上,我真正的最终目标是能够基于这个类创建一个新的PropertyInfo:
public class DynamicClass
{
public Type ObjectType { get; set; }
public List<string> PropertyNameList { get; set; }
public List<Type> PropertyTypeList { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我希望有人可以帮助我实现这一目标.提前谢谢了!
编辑:我忘了在GetProperties()方法之前添加o.GetType().谢谢Ilya Ivanov!
我正在调用SelectProperties方法,如下所示:
list = _queriable.Select(SelectProperties).ToList();
Run Code Online (Sandbox Code Playgroud)
该方法如下所示:
private Expression<Func<T, List<string>>> SelectProperties
{
get
{
return value => _properties.Select
(
prop => (prop.GetValue(value, new object[0]) ?? string.Empty).ToString()
).ToList();
} …Run Code Online (Sandbox Code Playgroud) 我有一个方便的实用程序方法,它接受代码并吐出内存中的程序集.(它使用CSharpCodeProvider,虽然我不认为这应该重要.)这个程序集像任何其他反射一样工作,但当与dynamic关键字一起使用时,似乎失败了RuntimeBinderException:
'object'不包含'Sound'的定义
例:
var assembly = createAssembly("class Dog { public string Sound() { return \"woof\"; } }");
var type = assembly.GetType("Dog");
Object dog = Activator.CreateInstance(type);
var method = type.GetMethod("Sound");
var test1Result = method.Invoke(dog, null); //This returns "woof", as you'd expect
dynamic dog2 = dog;
String test2Result = dog2.Sound(); //This throws a RuntimeBinderException
Run Code Online (Sandbox Code Playgroud)
有谁知道DLR无法处理这个问题的原因?有什么办法可以解决这个问题吗?
编辑:
createAssembly方法:
免责声明:其中一些内容包含扩展方法,自定义类型等.但它应该是不言自明的.
private Assembly createAssembly(String source, IEnumerable<String> assembliesToReference = null)
{
//Create compiler
var codeProvider = new CSharpCodeProvider();
//Set compiler …Run Code Online (Sandbox Code Playgroud) 我只是在探索java反射API,我遇到了以下代码片段
public class Main {
public static void main(String[] args) throws IllegalAccessException, NoSuchFieldException{
Field value=Integer.class.getDeclaredField("value");
value.setAccessible(true);
value.set(42, 43);
System.out.printf("six times seven %d%n",6*7);
System.out.printf("six times seven %d%n",42);
System.out.println(42);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
six times seven 43
six times seven 43
42
Run Code Online (Sandbox Code Playgroud)
我阅读了set方法的文档,该方法声明它为给定对象设置字段的值.但我无法理解代码的输出,因为它应该在所有情况下打印42.
任何人都可以深入了解代码中发生的事情吗?
PL/SQL中是否有一个函数来显示变量的确切类型,比如SQL中的DUMP函数?
我尝试了以下内容
DECLARE
l_variable INTEGER := 1;
BEGIN
DBMS_OUTPUT.PUT_LINE (DUMP (l_variable));
END;
Run Code Online (Sandbox Code Playgroud)
但它给出了以下错误:
PLS-00204:函数或伪列'DUMP'只能在SQL语句中使用
我正在编写一个组件,它在顶层通过反射调用方法.为了使我的组件更容易使用,我想捕获被调用方法抛出的任何异常并解开它们.
因此,我有类似的东西:
try { method.Invoke(obj, args); }
catch (TargetInvocationException ex) {
throw ex.InnerException;
}
Run Code Online (Sandbox Code Playgroud)
但是,这会吹走内部异常堆栈跟踪.我不能在throw这里使用(因为我正在重新抛出一个不同的异常对象).我可以在catch块中做些什么来确保原始异常类型,消息和堆栈跟踪都能通过?
我试图测试两个"容器"是否使用相同的高级类型.看下面的代码:
import scala.reflect.runtime.universe._
class Funct[A[_],B]
class Foo[A : TypeTag](x: A) {
def test[B[_]](implicit wt: WeakTypeTag[B[_]]) =
println(typeOf[A] <:< weakTypeOf[Funct[B,_]])
def print[B[_]](implicit wt: WeakTypeTag[B[_]]) = {
println(typeOf[A])
println(weakTypeOf[B[_]])
}
}
val x = new Foo(new Funct[Option,Int])
x.test[Option]
x.print[Option]
Run Code Online (Sandbox Code Playgroud)
输出是:
false
Test.Funct[Option,Int]
scala.Option[_]
Run Code Online (Sandbox Code Playgroud)
但是,我希望一致性测试能够成功.我究竟做错了什么?我如何测试更高级的类型?
澄清
在我的例子中,我正在测试的值(x: A在示例中)来自List[c.Expr[Any]]宏.所以任何依赖于静态分辨率的解决方案(就像我给出的那样)都无法解决我的问题.
我最近第一次使用异步(和.Net 4.5),我遇到了让我难过的东西.关于我可以在网上找到的VoidTaskResult类的信息不多,所以我来到这里是为了看看是否有任何关于发生了什么的想法.
我的代码如下所示.显然,这很简单.基本思想是调用异步的插件方法.如果它们返回Task,则异步调用没有返回值.如果他们返回Task <>,那么就有了.我们事先不知道它们是哪种类型,因此我们的想法是使用反射查看结果的类型(如果类型为Type <>,则IsGenericType为true)并使用动态类型获取值.
在我的真实代码中,我通过反射调用插件方法.我认为这不应该对我所看到的行为产生影响.
// plugin method
public Task yada()
{
// stuff
}
public async void doYada()
{
Task task = yada();
await task;
if (task.GetType().IsGenericType)
{
dynamic dynTask = task;
object result = dynTask.Result;
// do something with result
}
}
Run Code Online (Sandbox Code Playgroud)
这适用于上面显示的插件方法.IsGenericType为false(正如预期的那样).
但是,如果稍微更改插件方法的声明,IsGenericType现在返回true并且东西中断:
public async Task yada()
{
// stuff
}
Run Code Online (Sandbox Code Playgroud)
执行此操作时,行上会抛出以下异常(object result = dynTask.Result;):

如果你深入研究任务对象,它实际上似乎是类型.VoidTaskResult是线程名称空间中的私有类型,几乎没有任何内容.

我尝试更改我的调用代码:
public async void doYada()
{
Task task = yada();
await task;
if (task.GetType().IsGenericType)
{
object result = task.GetType().GetProperty("Result").GetMethod.Invoke(task, new …Run Code Online (Sandbox Code Playgroud) 请参考以下代码.当我运行代码时,我能够更改最终的非静态变量的值.但是,如果我尝试更改最终静态变量的值,那么它会抛出java.lang.IllegalAccessException.
我的问题是为什么它不会在非静态最终变量的情况下抛出异常,反之亦然.为什么不同?
import java.lang.reflect.Field;
import java.util.Random;
public class FinalReflection {
final static int stmark = computeRandom();
final int inmark = computeRandom();
public static void main(String[] args) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
FinalReflection obj = new FinalReflection();
System.out.println(FinalReflection.stmark);
System.out.println(obj.inmark);
Field staticFinalField = FinalReflection.class.getDeclaredField("stmark");
Field instanceFinalField = FinalReflection.class.getDeclaredField("inmark");
staticFinalField.setAccessible(true);
instanceFinalField.setAccessible(true);
instanceFinalField.set(obj, 100);
System.out.println(obj.inmark);
staticFinalField.set(FinalReflection.class, 101);
System.out.println(FinalReflection.stmark);
}
private static int computeRandom() {
return new Random().nextInt(5);
}
}
Run Code Online (Sandbox Code Playgroud) 考虑以下代码:
var future = new Future();
future.GetType().GetProperty(info.Name).SetValue(future, converted);
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,我们应该传递两个参数SetValue.首先,我们要设置其属性的对象.第二,新的价值.但我们选择了具体的财产.
为什么我们应该传递第一个参数来设置值,因为我们之前设置了未来的对象!?