English 中文(简体)
c 对通用模板类别进行思考
原标题:c# reflection on generic template class

根据我的法典样本:

public abstract class<T>
{
   public List<T> GetSomething(string q)
   {
      **List<T> list = new List<T>();**

      Type type = typeof(T);
      PropertyInfo[] props = type.GetProperties(BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance);

      foreach (PropertyInfo info in props)
      {
          // at this point I need to return information from a data source query
          // and build the members (set values) according to the returning results
          // which needs to be added to a list that contains T with each property
          // within set to a value. "Some Value" should be an object instance required
          // by the Type of the PropertyInfo.

          info.SetValue(type, "Some Value", null);
          **list.Add(type);**
      }
   }

   **return list;**
}

由于模板类型,无法进入(物体、物体、物体)? 我在此要问的是,我如何确定T中所含财产的价值?

Edit: 问题甚至使人感到困惑。 我对上述程序进行了修改,以反映我的直接需要。

Thanks, Eric

最佳回答

我看不出这有什么意义。 你试图在T的instance上设定财产(如你具有约束力的flags所示),但作为第一种论点,你通过<代码>(T)-aType-PropertyInfo.SetValue。 也许你指的是:

public abstract class Foo<T> 
{ 
   public List<T> GetSomethingFrom(T instance) 
   { 
      Type type = typeof(T); 
      PropertyInfo[] props = type.GetProperties(BindingFlags.Public |
           BindingFlags.IgnoreCase | BindingFlags.Instance); 

      foreach (PropertyInfo info in props) 
      { 
          info.SetValue(instance, "Some Value", null); 
      } 
   } 
} 

在此情况下,我们重新通过T到GetSomethingFrom方法,然后通过TetaValue。 后续行动

- Oisin

问题回答

可以说,你所设置的财产实际上也在扼杀之中,或者你要求SetaValue(实际上,“Some Value”是无效的)将消失。

看来,你正试图创建一种通用的物体初始器。 反省会发挥作用,但我建议调查该系统。 Linq.Expressions namespace. 你可以利用思考来建立一个拉布达特大萧条,即你能够动态地把这一方法汇编成一种方法,其性能将大大提高,而不是每次以反思的方式开始目标。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签