如果我有以下代码:
MyType<int> anInstance = new MyType<int>();
Type type = anInstance.GetType();
Run Code Online (Sandbox Code Playgroud)
通过查看类型变量,如何找出实例化的"anInstance"类型参数?可能吗 ?
可能重复:
查找传递给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) 我想通过反射选择正确的通用方法,然后调用它.
通常这很容易.例如
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'方法的正确版本?
我刚刚使用了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) 我有一些非null变量(例如en1)的Enum类型.问题是:如何获取与en1变量引用的枚举常量相关的注释?
是否有任何替代IsSubclassOf或IsAssignableFrom在C#Metro风格?
我正在尝试使这个代码在Metro上运行,但无法找到替代方案.
if ((ui.GetType() == type) || (ui.GetType().IsSubclassOf(type)))
{
return true;
}
Run Code Online (Sandbox Code Playgroud) 我需要使用反射调用类的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方法参数保持在超类型中并且仍然使用反射而无需在从类中获取方法时手动给出参数的类型?
这个问题随处可见谷歌,但我仍然遇到问题.这就是我想要做的.所以就像我的标题所说,我得到一个'对象不是声明类的错误的实例'.有任何想法吗?谢谢!
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) 例如
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#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(!)反射来获取当前方法名称.
reflection ×10
c# ×6
java ×4
.net ×2
android ×1
annotations ×1
asynchronous ×1
c#-6.0 ×1
enums ×1
nameof ×1
obfuscation ×1
proguard ×1
variables ×1