标签: reflection

反射 - 从System.Type实例获取通用参数

如果我有以下代码:

MyType<int> anInstance = new MyType<int>();
Type type = anInstance.GetType();
Run Code Online (Sandbox Code Playgroud)

通过查看类型变量,如何找出实例化的"anInstance"类型参数?可能吗 ?

.net c# reflection generic-type-argument

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

你如何获得变量的名称,因为它在声明中是物理输入的?

可能重复:
查找传递给C#中函数的变量名称

下面的课程包含现场城市.

我需要动态确定字段名称,因为它是在类声明中输入的,即我需要从对象城市的实例中获取字符串"city".

我试图通过检查其在DoSomething()中的类型来做到这一点,但在检查调试器中的Type的内容时找不到它.

可能吗?

public class Person
{
  public string city = "New York";

  public Person()
  {
  }


  public void DoSomething()
  {
    Type t = city.GetType();

    string field_name = t.SomeUnkownFunction();
    //would return the string "city" if it existed!
  }
}
Run Code Online (Sandbox Code Playgroud)

下面他们的答案中的一些人问我为什么要这样做.这就是原因.

在我的真实世界中,城市上方有一个自定义属性.

[MyCustomAttribute("param1", "param2", etc)]
public string city = "New York";
Run Code Online (Sandbox Code Playgroud)

我需要在其他代码中使用此属性.要获取属性,我使用反射.在反射代码中我需要输入字符串"city"

MyCustomAttribute attr;
Type t = typeof(Person);

foreach (FieldInfo field in t.GetFields())
{

  if (field.Name == "city")
  {
    //do stuff when we find the field that has …
Run Code Online (Sandbox Code Playgroud)

c# reflection variables

34
推荐指数
3
解决办法
9万
查看次数

选择具有反射的右通用方法

我想通过反射选择正确的通用方法,然后调用它.

通常这很容易.例如

var method = typeof(MyType).GetMethod("TheMethod");
var typedMethod = method.MakeGenericMethod(theTypeToInstantiate);
Run Code Online (Sandbox Code Playgroud)

但是,当方法存在不同的泛型重载时,问题就开始了.例如,System.Linq.Queryable类中的静态方法.'Where'方法有两种定义

static IQueryable<T> Where(this IQueryable<T> source, Expression<Func<T,bool>> predicate)
static IQueryable<T> Where(this IQueryable<T> source, Expression<Func<T,int,bool>> predicate)
Run Code Online (Sandbox Code Playgroud)

这说明GetMethod无法正常工作,因为它无法让两者黯然失色.因此,我想选择正确的.

到目前为止,我经常只采取第一种或第二种方法,这取决于我的需要.像这样:

var method = typeof (Queryable).GetMethods().First(m => m.Name == "Where");
var typedMethod = method.MakeGenericMethod(theTypeToInstantiate);
Run Code Online (Sandbox Code Playgroud)

但是我对此并不满意,因为我做了一个很大的假设,即第一种方法是正确的.我宁愿通过参数类型找到正确的方法.但我无法弄清楚如何.

我尝试传递'类型',但它没有用.

        var method = typeof (Queryable).GetMethod(
            "Where", BindingFlags.Static,
            null,
            new Type[] {typeof (IQueryable<T>), typeof (Expression<Func<T, bool>>)},
            null);
Run Code Online (Sandbox Code Playgroud)

所以有人知道如何通过反射找到'正确'的通用方法.例如,Queryable类的'Where'方法的正确版本?

c# reflection

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

Android中的Proguard和反射

我刚刚使用了proguard,但我试图通过反射实例化的类不起作用.

我有一个界面

Algorithm
Run Code Online (Sandbox Code Playgroud)

我通过这样的课程

AlgorithmFactory.SomeClassThatExtendsAlgorithmImpl.class
Run Code Online (Sandbox Code Playgroud)

该类实例化如下

public ArrayList<Algorithm> getAlgorithms(Context cnx) {
ArrayList<Algorithm> list = new ArrayList<Algorithm>();

for(Class<? extends Algorithm> alg: algorithms) {

    try {
        Constructor<? extends Algorithm> c = alg.getConstructor(Context.class);
        list.add(c.newInstance(cnx));
    } catch (IllegalArgumentException e) {
        Log.e(TAG, "IllegalArgumentException", e);
        throw new IllegalStateException("There was a problem creating the Algorithm class");
    } catch (InvocationTargetException e) {
        Log.e(TAG, "InvocationTargetException", e);
        throw new IllegalStateException("There was a problem creating the Algorithm class");
    } catch (InstantiationException e) {
        Log.e(TAG, "InstantiationException", e);
        throw new IllegalStateException("There was a …
Run Code Online (Sandbox Code Playgroud)

java reflection obfuscation android proguard

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

获取枚举类型变量的注释

我有一些非null变量(例如en1)的Enum类型.问题是:如何获取与en1变量引用的枚举常量相关的注释?

java reflection enums annotations

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

C#Metro风格的IsSubclassOf或IsAssignableFrom的任何替代方案

是否有任何替代IsSubclassOf或IsAssignableFrom在C#Metro风格?

我正在尝试使这个代码在Metro上运行,但无法找到替代方案.

if ((ui.GetType() == type) || (ui.GetType().IsSubclassOf(type)))
{
    return true;
}
Run Code Online (Sandbox Code Playgroud)

.net c# reflection microsoft-metro windows-runtime

34
推荐指数
2
解决办法
9277
查看次数

使用java反射调用setter方法

我需要使用反射调用类的setter方法,代码如下:

try {             
   Method method = myObj.getClass().getMethod("set" + fieldName, new Class[] { value.getClass() });               
   method.invoke(myObj, value);
     } catch (Exception ex) {
         ex.printStackTrace();
     }
Run Code Online (Sandbox Code Playgroud)

的value是一个ArrayList以及设置器方法如下:

public void setNames(List<String> names){
    this.names = names;
}
Run Code Online (Sandbox Code Playgroud)

java.lang.NoSuchMethodException运行此代码时抛出A ,但当setter方法参数类型更改为ArrayListfrom时List,执行正常.有没有办法将setter方法参数保持在超类型中并且仍然使用反射而无需在从类中获取方法时手动给出参数的类型?

java reflection

34
推荐指数
4
解决办法
7万
查看次数

Java Reflection - Object不是声明类的实例

这个问题随处可见谷歌,但我仍然遇到问题.这就是我想要做的.所以就像我的标题所说,我得到一个'对象不是声明类的错误的实例'.有任何想法吗?谢谢!

Main.java

Class<?> base = Class.forName("server.functions.TestFunction");
Method serverMethod = base.getMethod("execute", HashMap.class);
serverMethod.invoke(base, new HashMap<String, String>());
Run Code Online (Sandbox Code Playgroud)

TestFunction.java

package server.functions;

import java.util.HashMap;
import java.util.Map;

import server.*;

public class TestFunction extends ServerBase {

    public String execute(HashMap<String, String> params)
    {
        return "Test function successfully called";
    }
}
Run Code Online (Sandbox Code Playgroud)

java reflection

34
推荐指数
2
解决办法
6万
查看次数

如何通过反射判断C#方法是否异步/等待?

例如

class Foo { public async Task Bar() { await Task.Delay(500); } }
Run Code Online (Sandbox Code Playgroud)

如果我们反思这个类和方法,我如何确定这是否是一个真正的async/await方法,而不仅仅是一个碰巧返回任务的方法?

class Foo { public Task Bar() { return Task.Delay(500); } }
Run Code Online (Sandbox Code Playgroud)

c# reflection asynchronous

34
推荐指数
3
解决办法
8181
查看次数

使用nameof获取当前方法的名称

浏览,搜索和希望但找不到直接答案.

无论如何在C#6.0中使用nameofwithouth指定方法名称来获取当前方法名称?

我将测试结果添加到这样的字典中:

Results.Add(nameof(Process_AddingTwoConsents_ThreeExpectedRowsAreWrittenToStream), result);
Run Code Online (Sandbox Code Playgroud)

我希望如果我不必明确指定方法名称,那么我可以复制+粘贴该行,这是一个非工作的例子:

Results.Add(nameof(this.GetExecutingMethod()), result);
Run Code Online (Sandbox Code Playgroud)

如果可能的话我不想使用Reflection.

UPDATE

这不是(如建议的)这个问题的副本.我问是否明确可以使用nameofwithout(!)反射来获取当前方法名称.

c# reflection c#-6.0 nameof

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