在具有泛型参数的抽象类上使用反射来获取静态值. [英] Using reflection on a abstract class with genericparameters to get a static value.

查看:88
本文介绍了在具有泛型参数的抽象类上使用反射来获取静态值.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个C#/C ++桥(c#在桌面上运行,而c ++直接在硬件上运行),该桥使用抽象类和接口从特殊的c#文件自动生成,以使用反射描述与生成器的通信桥. />
在尝试删除一些用于执行此操作的额外属性并使它们变得更像C#时,就像我遇到问题一样.

有没有一种方法可以使用反射来获取"DefaultWindowSize"字段的值?

We have a C#/C++ bridge (c# is running on a desktop and the c++ directly on hardware) that is auto generated from special c# files using abstract classes and interfaces to describe the communication bridge to our generator using reflexion.

In trying to remove some of the extra attributes used to do so and make them more c# like I hit a problem.

Is there a way of getting the value of the ''DefaultWindowSize'' field using reflection?

public abstract class Averager<InputType>
{
    //[Static, Value(10)] attributes removed
    public static int DefaultWindowSize = 10;

    public abstract AveragingMode AveragingMode { get; set; }
    public abstract uint NumberOfSamples { get; }
}



我尝试使用:



I have tried using:

FieldInfo[] info = currentClass.GetFields(BindingFlags.Static);
object defueltValue = info[0].GetValue(null);



但这给了我一个例外:
不能对类型为Type.ContainsGenericParameters为true的字段执行最新的绑定操作."



but this gives me a exception:
"Late bound operations cannot be performed on fields with types for which Type.ContainsGenericParameters is true."

推荐答案

我刚刚将这个小样本放到一起,演示了如何从抽象的通用类中获取静态字段:

I''ve just thrown this small sample together which demonstrates how to fetch the static fields from an abstract generic class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace AbstractGeneric
{
    class Program
    {
        static void Main(string[] args)
        {
            Type myAbstractGenericType = typeof(AbstractGeneric<>);
            Type[] types = { typeof(int) };
            Type constructed = myAbstractGenericType.MakeGenericType(types);
            FieldInfo[] fieldInfos = constructed.GetFields(
                BindingFlags.NonPublic |
                BindingFlags.Public |
                BindingFlags.Static);
            foreach (FieldInfo fi in fieldInfos)
            {
                Console.WriteLine("Name: {0}  Value: {1}", fi.Name, fi.GetValue(null));
            }
            Console.ReadLine();
        }
    }
    public abstract class AbstractGeneric<T>
    {
        private static int anInt = 12345;
        private static String aString = "XXYYZZ";
        public abstract T WhatEver { get; set; }
    }
}



我希望这能帮到您.如果对此有任何疑问,请随时在下面添加评论.

最好的问候,

—MRB



I hope this will help you. If you have any questions regarding this, feel free to add a comment below.

Best Regards,

—MRB


这篇关于在具有泛型参数的抽象类上使用反射来获取静态值.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆