×

Loading...
Ad by
  • 推荐 OXIO 加拿大高速网络,最低月费仅$40. 使用推荐码 RCR37MB 可获得一个月的免费服务
Ad by
  • 推荐 OXIO 加拿大高速网络,最低月费仅$40. 使用推荐码 RCR37MB 可获得一个月的免费服务

改严谨一些:hashtable 可以让你基于 key 来访问,而不是 index

本文发表在 rolia.net 枫下论坛Hashtable Class
A Hashtable class is a weakly typed collection of key-value pairs. This means that for each object you add to the Hashtable, you need to provide a key that uniquely identifies the object. The Hashtable lets you quickly get an object out of the collection by using it's key. The following code is an example of how to add customers to a Hashtable. The key that will be used is the (imaginary) customer code.

Dim customers As New Hashtable
customers.Add("J", New Customer("Jan", "111"))
customers.Add("N", New Customer("Nele", "222"))


You'll notice that when adding a customer to the Hashtable, you have to provide an extra parameter; this parameter is the key, which in our example is a String but could be almost any type. So why is this collection called a Hashtable? Well, what happens when you add a key with a corresponding object is that of the key object, the hash value is calculated. The hash value is a numeric value that can uniquely identify the key object. So the key object is not stored in the collection, only it's hash value. To get an item out of your Hashtable, again you use the key object to retrieve it:更多精彩文章及讨论,请光临枫下论坛 rolia.net
Report

Replies, comments and Discussions:

  • 工作学习 / IT技术讨论 / 急问:.NET 中 INVOKEMEMBER的用法。谢谢先。
    现在有类:
    Class classA
    public property PropertyA(byval pa1 as integer, byval pa2 as integer)
    .
    .
    End Property
    Edn class

    我利用一个hashtable 变量hashtableA从xml文件里取出了这两个参数的值,如下:
    hashtableA.add(pa1, ValueofPa1)
    hashtableB.add(pa2, ValueofPa2)

    最后,我想利用invokemember取得PropertyA的值,请问如何实现。
    • up。
      • up
    • 不明白:
      public property ProteryA(...)
      这第一个property是什么?

      classA.PropertyA(..)应该就是值啊。
      • 应该是这样:
        public readonly Property ProperyA (pa1 as integer, pa2 as integer)
        get
        propertyA=...
        (这个值是由pa1和pa2一起决定的。比如 propertyA=findrow (pa1,pa2)
        end get
        end property
        • 也许这个例子是你想要得??
          本文发表在 rolia.net 枫下论坛Type.InvokeMember Method [C#]
          See Also
          Type Class | Type Members | System Namespace
          Language
          C#

          C++

          JScript

          Visual Basic

          Show All
          Invokes a specific member of the current Type.

          Overload List
          Invokes the specified member, using the specified binding constraints and matching the specified argument list.

          [Visual Basic] Overloads Public Function InvokeMember(String, BindingFlags, Binder, Object, Object()) As Object
          [C#] public object InvokeMember(string, BindingFlags, Binder, object, object[]);
          [C++] public: Object* InvokeMember(String*, BindingFlags, Binder*, Object*, Object[]);
          [JScript] public function InvokeMember(String, BindingFlags, Binder, Object, Object[]) : Object;
          Invokes the specified member, using the specified binding constraints and matching the specified argument list and culture.

          [Visual Basic] Overloads Public Function InvokeMember(String, BindingFlags, Binder, Object, Object(), CultureInfo) As Object
          [C#] public object InvokeMember(string, BindingFlags, Binder, object, object[], CultureInfo);
          [C++] public: Object* InvokeMember(String*, BindingFlags, Binder*, Object*, Object[], CultureInfo*);
          [JScript] public function InvokeMember(String, BindingFlags, Binder, Object, Object[], CultureInfo) : Object;
          When overridden in a derived class, invokes the specified member, using the specified binding constraints and matching the specified argument list, modifiers and culture.

          [Visual Basic] Overloads MustOverride Public Function InvokeMember(String, BindingFlags, Binder, Object, Object(), ParameterModifier(), CultureInfo, String()) As Object Implements IReflect.InvokeMember
          [C#] public abstract object InvokeMember(string, BindingFlags, Binder, object, object[], ParameterModifier[], CultureInfo, string[]);
          [C++] public: virtual Object* InvokeMember(String*, BindingFlags, Binder*, Object*, Object[], ParameterModifier[], CultureInfo*, String*[]) = 0;
          [JScript] public abstract function InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]) : Object;
          Example
          [Visual Basic, C#, JScript] Here are syntax examples using InvokeMember to invoke, get, and set various members.

          [Visual Basic, C#, JScript] Note This example shows how to use one of the overloaded versions of InvokeMember. For other examples that might be available, see the individual overload topics.
          [Visual Basic]
          Imports System
          Imports System.IO
          Imports System.Reflection

          Public Class Sample

          Public Sub Method()

          'Call a static method
          Dim t As Type = GetType(TestClass)
          t.InvokeMember("SayHello", BindingFlags.Public Or _
          BindingFlags.InvokeMethod Or BindingFlags.Static, Nothing, Nothing, _
          New Object() {})

          'Call an instance method
          Dim c As New TestClass()
          c.GetType().InvokeMember("AddUp", BindingFlags.Public Or _
          BindingFlags.InvokeMethod, Nothing, c, New Object() {})
          c.GetType().InvokeMember("AddUp", BindingFlags.Public Or _
          BindingFlags.InvokeMethod, Nothing, c, New Object() {})

          'Call a method with arguments
          Dim args() As Object = {100.09, 184.45}
          Dim result As Object
          result = t.InvokeMember("ComputeSum", BindingFlags.Public Or _
          BindingFlags.InvokeMethod Or BindingFlags.Static, Nothing, _
          Nothing, args)
          Console.WriteLine("{0} + {1} = {2}", args(0), args(1), result)

          'Get a field value
          result = t.InvokeMember("Name", BindingFlags.Public Or _
          BindingFlags.GetField, Nothing, c, New Object() {})
          Console.WriteLine("Name == {0}", result)

          'Set a field
          t.InvokeMember("Name", BindingFlags.Public Or _
          BindingFlags.SetField, Nothing, c, New Object() {"NewName"})
          result = t.InvokeMember("Name", BindingFlags.Public Or _
          BindingFlags.GetField, Nothing, c, New Object() {})
          Console.WriteLine("Name == {0}", result)

          'Get an indexed property value
          Dim index As Integer = 3
          result = t.InvokeMember("Item", BindingFlags.Public Or _
          BindingFlags.GetProperty, Nothing, c, New Object() {index})
          Console.WriteLine("Item[{0}] == {1}", index, result)

          'Set an indexed property value
          index = 3
          t.InvokeMember("Item", BindingFlags.Public Or _
          BindingFlags.SetProperty, Nothing, c, New Object() {index, "NewValue"})
          result = t.InvokeMember("Item", BindingFlags.Public Or _
          BindingFlags.GetProperty, Nothing, c, New Object() {index})
          Console.WriteLine("Item[{0}] == {1}", index, result)

          'Get a field or property
          result = t.InvokeMember("Name", BindingFlags.Public Or _
          BindingFlags.GetField Or BindingFlags.GetProperty, Nothing, c, _
          New Object() {})
          Console.WriteLine("Name == {0}", result)
          result = t.InvokeMember("Value", BindingFlags.Public Or _
          BindingFlags.GetField Or BindingFlags.GetProperty, Nothing, c, _
          New Object() {})
          Console.WriteLine("Value == {0}", result)

          'Call a method using named arguments
          Dim argValues() As Object = {"Mouse", "Micky"}
          Dim argNames() As String = {"lastName", "firstName"}
          t.InvokeMember("PrintName", BindingFlags.Public Or _
          BindingFlags.InvokeMethod, Nothing, Nothing, argValues, Nothing, _
          Nothing, argNames)

          'Call the default member of a type
          Dim t3 As Type = GetType(TestClass2)
          t3.InvokeMember("", BindingFlags.Public Or BindingFlags.InvokeMethod, _
          Nothing, New TestClass2(), New Object() {})

          'Invoking a ByRef member
          Dim m As MethodInfo = t.GetMethod("Swap")
          args = New Object(2) {}
          args(0) = 1
          args(1) = 2
          m.Invoke(New TestClass(), args)
          Console.WriteLine("{0}, {1}", args(0), args(1))
          Console.WriteLine(Microsoft.VisualBasic.ControlChars.CrLf & _
          "Press Return to exit.")
          Console.Read()
          End Sub
          End Class

          ' Class added so sample will compile
          Public Class TestClass
          End Class

          ' Class added so sample will compile
          Public Class TestClass2
          End Class
          [C#]
          using System;
          using System.IO;
          using System.Reflection;

          public class Sample
          {
          public void Method()
          {

          //Call a static method
          Type t = typeof (TestClass);
          t.InvokeMember ("SayHello", BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Static, null, null, new object [] {});

          //Call an instance method
          TestClass c = new TestClass ();
          c.GetType().InvokeMember ("AddUp", BindingFlags.Public | BindingFlags.InvokeMethod, null, c, new object [] {});
          c.GetType().InvokeMember ("AddUp", BindingFlags.Public | BindingFlags.InvokeMethod, null, c, new object [] {});

          //Call a method with arguments
          object [] args = new object [] {100.09, 184.45};
          object result;
          result = t.InvokeMember ("ComputeSum", BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Static, null, null, args);
          Console.WriteLine ("{0} + {1} = {2}", args[0], args[1], result);

          //Get a field value
          result = t.InvokeMember ("Name", BindingFlags.Public | BindingFlags.GetField, null, c, new object [] {});
          Console.WriteLine ("Name == {0}", result);

          //Set a field
          t.InvokeMember ("Name", BindingFlags.Public |BindingFlags.SetField, null, c, new object [] {"NewName"});
          result = t.InvokeMember ("Name", BindingFlags.Public |BindingFlags.GetField, null, c, new object [] {});
          Console.WriteLine ("Name == {0}", result);

          //Get an indexed property value
          int index = 3;
          result = t.InvokeMember ("Item", BindingFlags.Public |BindingFlags.GetProperty , null, c, new object [] {index});
          Console.WriteLine ("Item[{0}] == {1}", index, result);

          //Set an indexed property value
          index = 3;
          t.InvokeMember ("Item", BindingFlags.Public |BindingFlags.SetProperty, null, c, new object [] {index, "NewValue"});
          result = t.InvokeMember ("Item", BindingFlags.Public |BindingFlags.GetProperty , null, c, new object [] {index});
          Console.WriteLine ("Item[{0}] == {1}", index, result);

          //Get a field or property
          result = t.InvokeMember ("Name", BindingFlags.Public |BindingFlags.GetField | BindingFlags.GetProperty, null, c, new object [] {});
          Console.WriteLine ("Name == {0}", result);
          result = t.InvokeMember ("Value", BindingFlags.Public |BindingFlags.GetField | BindingFlags.GetProperty, null, c, new object [] {});
          Console.WriteLine ("Value == {0}", result);

          //Call a method using named arguments
          object[] argValues = new object [] {"Mouse", "Micky"};
          String [] argNames = new String [] {"lastName", "firstName"};
          t.InvokeMember ("PrintName", BindingFlags.Public |BindingFlags.InvokeMethod, null, null, argValues, null, null, argNames);

          //Call the default member of a type
          Type t3 = typeof (TestClass2);
          t3.InvokeMember ("", BindingFlags.Public |BindingFlags.InvokeMethod, null, new TestClass2(), new object [] {});

          //Invoking a ByRef member
          MethodInfo m = t.GetMethod("Swap");
          args = new object[2];
          args[0] = 1;
          args[1] = 2;
          m.Invoke(new TestClass(),args);
          Console.WriteLine ("{0}, {1}", args[0], args[1]);
          Console.WriteLine ("\r\nPress Return to exit.");
          Console.Read();

          }
          }

          // Class added so sample will compile
          public class TestClass {}

          // Class added so sample will compile
          public class TestClass2 {}更多精彩文章及讨论,请光临枫下论坛 rolia.net
          • thanks. 这一步完成了。
            • 我刚看了些help,说invokememeber的对象must be accessible。你那个property是readonly,估计就不行了八?
              • 我没用过 invokemember before. :(
                • 我要用很多invokemember,很灵活。这个例子不错。//还有一个问题,用hashtable有什么特别的好处呢。再帮我找个例子?:)
                  • 好奇问一下:为什么得用 InvokeMember? 没可能用 virtual 么? property 也支持 virtual 的。关于 hashtable 我觉得就是找起来快一些,能保证其唯一性,如果 key 不是 unique 根本不能 add 进去。
                    • 改严谨一些:hashtable 可以让你基于 key 来访问,而不是 index
                      本文发表在 rolia.net 枫下论坛Hashtable Class
                      A Hashtable class is a weakly typed collection of key-value pairs. This means that for each object you add to the Hashtable, you need to provide a key that uniquely identifies the object. The Hashtable lets you quickly get an object out of the collection by using it's key. The following code is an example of how to add customers to a Hashtable. The key that will be used is the (imaginary) customer code.

                      Dim customers As New Hashtable
                      customers.Add("J", New Customer("Jan", "111"))
                      customers.Add("N", New Customer("Nele", "222"))


                      You'll notice that when adding a customer to the Hashtable, you have to provide an extra parameter; this parameter is the key, which in our example is a String but could be almost any type. So why is this collection called a Hashtable? Well, what happens when you add a key with a corresponding object is that of the key object, the hash value is calculated. The hash value is a numeric value that can uniquely identify the key object. So the key object is not stored in the collection, only it's hash value. To get an item out of your Hashtable, again you use the key object to retrieve it:更多精彩文章及讨论,请光临枫下论坛 rolia.net
                      • 那我就有一个问题:有必要用hashtable来传递参数么。
                        • 有的,看什么情形, 看见过例子的。
                          • 我就是说,我上面那个invokemember的例子。
                    • invokemember 更灵活,property, method, enumeration, 还有nested property都可以用invokemember。
                      • 一般好像只有事先实在不知道有哪些 property 或 method 才可能需要用 reflection。
                        • 恩,我现在就是如此。再问:我如何从hashtable按我存入的顺序取出value的值来呢。
                          • use queue or stack instead...
                            • 谢谢。后来发现用hashtable 是必要的。用两个数组可以得到keys/values,这样就可以作为invokemember的参数了。
                        • 我用了copyto,试验了用for each key,取得的值都是按key值字符顺序。谢谢。