标签: reflection

如何创建一个能够包装实例,类和静态方法的Python类装饰器?

我想创建一个Python 类装饰器(*),它能够无缝地包装类可能具有的所有方法类型:实例,类和静态.

这是我现在的代码,其中的部分打破了它:

def wrapItUp(method):
    def wrapped(*args, **kwargs):
        print "This method call was wrapped!"
        return method(*args, **kwargs)
    return wrapped

dundersICareAbout = ["__init__", "__str__", "__repr__"]#, "__new__"]

def doICareAboutThisOne(cls, methodName):
    return (callable(getattr(cls, methodName))
            and (not (methodName.startswith("__") and methodName.endswith("__"))
            or methodName in dundersICareAbout))

def classDeco(cls):
    myCallables = ((aname, getattr(cls, aname)) for aname in dir(cls) if doICareAboutThisOne(cls, aname))
    for name, call in myCallables:
        print "*** Decorating: %s.%s(...)" % (cls.__name__, name)
        setattr(cls, name, wrapItUp(call))
    return cls

@classDeco
class SomeClass(object):

    def instanceMethod(self, p):
        print "instanceMethod: …
Run Code Online (Sandbox Code Playgroud)

python reflection instrumentation decorator

7
推荐指数
1
解决办法
1542
查看次数

获取扩展方法中第一个参数的名称?

string thing = "etc";
thing = thing.GetName();
//now thing == "thing"
Run Code Online (Sandbox Code Playgroud)

这甚至可能吗?

public static string GetName(this object obj)
{
    return ... POOF! //should == "thing"
}
Run Code Online (Sandbox Code Playgroud)

.net c# reflection extension-methods stack-frame

7
推荐指数
2
解决办法
1327
查看次数

使用从string中提取的参数调用函数

我正在看以下问题:

我得到格式如下的字符串:

functionname_parameter1_parameter2_parameter3
otherfunctionname_parameter1_parameter2
.
.
.
Run Code Online (Sandbox Code Playgroud)

我想用给定的参数调用函数.所以假设我有一个功能测试:

void test(int x, float y, std::string z) {}
Run Code Online (Sandbox Code Playgroud)

我收到一条消息:

test_5_2.0_abc
Run Code Online (Sandbox Code Playgroud)

那么我想像这样自动调用函数测试:

test(5, 2.0, "abc");
Run Code Online (Sandbox Code Playgroud)

您是否有任何关于如何在C++中实现此目的的提示?

c++ reflection binding parsing function

7
推荐指数
1
解决办法
4466
查看次数

从表达式树中提取方法名称?

我正在尝试实现以下模式函数:

MethodInfo GetMethod(      
  Expression<Func<TTarget, EventHandler<TEventArgs>>> method)
Run Code Online (Sandbox Code Playgroud)

如果需要,我可以提供TTarget的实例

所需的用法是:

public static void Main(string[] args)
{
    var methodInfo = GetMethod<Program, EventArgs>(t => t.Method);
    Console.WriteLine("Hello, world!");
}

private void Method(object sender, EventArgs e)
{
}
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止所尝试的:

private static MethodInfo GetMethod(TTarget target, Expression<Func<TTarget, EventHandler<TEventArgs>>> method)
{
  var lambda = method as LambdaExpression;
  var body = lambda.Body as UnaryExpression;
  var call = body.Operand as MethodCallExpression;
  var mInfo = call.Method as MethodInfo;

  Console.WriteLine(mInfo);

  throw new NotImplementedException();
}
Run Code Online (Sandbox Code Playgroud)

打印出来:

System.Delegate CreateDelegate(System.Type, System.Object, System.Reflection.Met hodInfo)

.net c# linq reflection expression-trees

7
推荐指数
1
解决办法
2127
查看次数

Objective C可以在运行时(反射)确定调用者对象引用吗?

据我所知,Objective C是一种比C#或Java更动态的语言.在C#中,您只能知道调用者对象的类(使用stacktrace),而不知道调用者本身的实例引用.

Objective C对此更有能力吗?

更新:我在这里查看了另一篇文章如何在Objective-C中确定我的方法的"调用者"?.据我所知,它只给出了类名.我坚持认为我只对类名不感兴趣,而是通过获取调用者实例本身的引用.

reflection objective-c ios

7
推荐指数
2
解决办法
5109
查看次数

将.mat文件中的变量加载到不同名称的变量中

假设我有一个.mat文件,其中包含几个相同结构的实例,每个实例都有一个不同的变量名.

我想处理文件中找到的每个实例(我发现使用whos('-file' ...).我希望load能让我指定一个变量的目的地名称,这样我就不用担心碰撞了(因此我不必编写自修改代码eval).

执行此操作的强力方法似乎是创建一个辅助函数,使用名称希望与.mat内容不冲突的变量,可以执行以下操作:

  1. 是否whos在文件上获取包含的名称.
  2. 迭代加载每个包含的结构.
  3. 用于eval将加载的结构分配到单元数组中(其中数组的一列包含.mat文件的结构名称,而相应的列包含.mat文件中每个结构的实际内容).

有没有更优雅的方式来完成同样的事情?

reflection file-io matlab

7
推荐指数
2
解决办法
9655
查看次数

在C#中,找出一个类是否具有属性的最佳方法是什么(使用反射)

我上课了

 public class Car
 {
       public string Name {get;set;}
       public int Year {get;set;}
 }
Run Code Online (Sandbox Code Playgroud)

在单独的代码中,我有一个字段名称作为字符串(让我们使用"年")作为一个例子.

我想做这样的事情

   if (Car.HasProperty("Year")) 
Run Code Online (Sandbox Code Playgroud)

这将弄清楚汽车对象上是否有一个Year字段.这将返回真实.

   if (Car.HasProperty("Model"))
Run Code Online (Sandbox Code Playgroud)

将返回false.

我看到代码循环遍历属性,但想看看是否有更简洁的方法来确定是否存在单个字段.

c# reflection

7
推荐指数
2
解决办法
8202
查看次数

为什么Type.GetFields()不返回基类中的后备字段?

在C#中,如果使用Type.GetFields()表示派生类的类型,它将返回a)派生类中所有显式声明的字段,b)派生类中自动属性的所有支持字段和c)基础中所有显式声明的字段类.

为什么缺少基类中自动属性的d)支持字段?

例:

public class Base {
    public int Foo { get; set; }
}
public class Derived : Base {
    public int Bar { get; set; }
}
class Program {
    static void Main(string[] args) {
        FieldInfo[] fieldInfos = typeof(Derived).GetFields(
            BindingFlags.Public | BindingFlags.NonPublic |
            BindingFlags.Instance | BindingFlags.FlattenHierarchy
        );
        foreach(FieldInfo fieldInfo in fieldInfos) {
            Console.WriteLine(fieldInfo.Name);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这将只显示Bar的支持字段,而不是Foo.

c# reflection properties backing-field

7
推荐指数
2
解决办法
6601
查看次数

Ruby Metaprogramming方法列表?

刚开始学习Ruby元编程.看看Object.methods我得到:

Object.methods => [
:allocate, 
:new, 
:superclass, 
:freeze, 
:===, 
:==, 
:<=>, 
:<, 
:<=, 
:>, 
:>=, 
:to_s, 
:included_modules, 
:include?, 
:name, 
:ancestors, 
:instance_methods, 
:public_instance_methods, 
:protected_instance_methods, 
:private_instance_methods, 
:constants, 
:const_get, 
:const_set, 
:const_defined?, 
:const_missing, 
:class_variables, 
:remove_class_variable, 
:class_variable_get, 
:class_variable_set, 
:class_variable_defined?, 
:module_exec, 
:class_exec, 
:module_eval, 
:class_eval, 
:method_defined?, 
:public_method_defined?, 
:private_method_defined?, 
:protected_method_defined?, 
:public_class_method, 
:private_class_method, 
:autoload, 
:autoload?, 
:instance_method, 
:public_instance_method, 
:nil?, 
:=~, 
:!~, 
:eql?, 
:hash, 
:class, 
:singleton_class, 
:clone, 
:dup, 
:initialize_dup, 
:initialize_clone, 
:taint, 
:tainted?, 
:untaint, 
:untrust, 
:untrusted?, 
:trust, 
:frozen?, 
:inspect, 
:methods, 
:singleton_methods, 
:protected_methods, 
:private_methods, 
:public_methods, 
:instance_variables, 
:instance_variable_get, 
:instance_variable_set, 
:instance_variable_defined?, 
:instance_of?, 
:kind_of?, 
:is_a?, 
:tap, …
Run Code Online (Sandbox Code Playgroud)

ruby reflection methods metaprogramming object

7
推荐指数
2
解决办法
735
查看次数

Activator.CreateInstance(...)未找到参数化构造函数

给出以下示例代码;

class Program
{
    static void Main(string[] args)
    {
        var results = GetChildren().ToList();
    }

    static IEnumerable<MyBaseClass> GetChildren()
    {
        return Assembly.GetExecutingAssembly()
            .GetTypes()
            .Where(t => t.BaseType == typeof(MyBaseClass))
            .Select(o => (MyBaseClass)Activator.CreateInstance(o, null));
    }
}

abstract class MyBaseClass
{ }

class MyChildClass : MyBaseClass
{
    public MyChildClass(object paramOne)
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误;

MissingMethodException:找不到类型"CreateInstanceCtorIssue.MyChildClass"的构造函数.

但是,如果我添加一个无参数构造函数,它会创建对象OK.

我试图弄清楚为什么我要为CreateInstance提供的参数不会导致它找到正确的构造函数.有人有任何想法吗?

c# reflection

7
推荐指数
1
解决办法
5977
查看次数