Working with Variants in Visual Basic

来源:互联网 发布:两个表格相同数据合并 编辑:程序博客网 时间:2024/05/17 06:52

Post from http://zone.ni.com/devzone/cda/tut/p/id/2949

Variant的巧妙应用,让我们在VB中实现了C++的模板。 妙,强!


What Is a Variant?

A Variant data type is self-describing data – it contains the actual value of the data and metadata, which is information about how Visual Basic uses and stores the data. Listed below are some facts about Variants and how Visual Basic handles Variant data:
  • Variant data is not typeless. Think of a Variant variable as one that can change type during runtime rather than as a variable without a type.
  • Visual Basic coerces Variant data as needed to perform comparisons and operations.
  • Visual Basic stores and maintains Variants using an internal representation of a specific data type. Although the following list is not comprehensive, it includes the most used types of data:

Numerical – Variants can store any integer or real number value ranging from -1.797693134862315E308 to -4.94066E-324 for negative values and from 4.94066E-324 to 1.797693134862315E308 for positive values. You can store the following numerical types as Variants: Integer, Long (long integer), Single (single-precision floating point), Double (double-precision floating point), Date/Time, and Currency.

String – Variants can hold character, alphanumeric, and numeric strings. Character and alphanumeric strings are treated as string data types. Numeric strings are treated as numerical data types.

Note Remember that Visual Basic coerces Variant data as needed to complete comparisons and operations. If you use the + operator on a numerical string and a number or numerical string, Visual Basic adds the two numbers. If you use the + operator on two character or alphanumeric strings, Visual Basic concatenates the values. However, if one of the strings is numerical and the other contains characters, Visual Basic tries to convert the character string into a number and add the two values. If Visual Basic cannot convert the string to a number, it returns a type mismatch error.

Arrays – You can have a Variant that contains an array or an array that contains Variant elements. If you work with a Variant that contains an array, remember to perform array operations on the data. That is, perform the operation on each element in the array. If you are working with an array of Variant elements, remember that elements can be of the same type of data or different types of data.

  • You can determine a Variant variable’s internal representation with the Visual Basic VarType and TypeName functions. See the How Do I Determine the Internal Representation of Variant Variables? section of this document for information about using these functions.
  • Variant data types can consume more memory and slow performance if they must be converted to different data types several times.To save memory and increase overall performance, consider explicitly declaring all variables.

ComponentWorks makes it easy to work with data in Visual Basic because most input and output parameters are Variants. For example, when you acquire data from a ComponentWorks Analog Input (CWAI) control, the control returns Variant data. Since the ComponentWorks Graph (CWGraph) accepts Variant data, you can plot the acquired data on the graph without having to first process it. You can then perform analysis on the Variant data and share the Variant data results over the network using the ComponentWorks DataSocket (CWDataSocket) control.

Why Use Variants?


Variant data simplifies programming by minimizing the amount of code you have to write.
  • By passing data as Variant data, you can use the same procedures and functions to process data with different internal representations without converting any data. That means you don’t have to create three separate procedures to perform the operations with three different types of data.

For example, when you acquire data with a ComponentWorks DAQ control, the data is returned as a Variant. You can pass that Variant – no matter what type of data it is holding – to other controls to visualize, analyze, or share. To visualize the data, call the CWGraph.PlotY method and pass it a Variant. The PlotY method visualizes the Variant data on the plot area, whether the data is an array of integers or an array of doubles. You don’t have to learn and call separate methods if the type of your data changes.
  • You don’t have to explicitly declare variables. Visual Basic automatically creates a Variant variable when you use undeclared variable names in your code.

Note Although not explicitly declaring variables saves code, it can make debugging more difficult. For example, if you mistype a variable name, Visual Basic declares it as a new Variant rather than generating an error that you have an undeclared variable. Use the Option Explicit statement to make Visual Basic verify that all variables are explicitly declared. If you attempt to use an undeclared variable name, Visual Basic generates an error at compile time.
  • Variant data simplifies passing data between applications in different environments, such as Microsoft Visual C++ or Borland Delphi. Although different application development environments might have different internal representations for specific data types, most accept and store Variant data the same way.

    How Do I Pass Variants to ComponentWorks controls?

How can you know what Variants to pass in and what you’ll get back? ComponentWorks controls are very flexible — you can pass nearly any type of data to a ComponentWorks control. The following list offers guidelines for passing data to some of the ComponentWorks controls:
  • User Interface – You can pass Variants of any numerical type: singles, doubles, longs, and so on. The controls coerce the Variant data as needed for the operation you perform. The CWButton, CWKnob, CWSlide, and CWNumEdit controls store numerical values as doubles. The CWGraph control accepts single points, one-dimensional arrays, and two-dimensional arrays. If you need to perform operations using a different data type, convert the value property with one of the Visual Basic conversion functions.
  • I/O (hardware) controls – ComponentWorks I/O data is passed as Variant data. For example, if you are acquiring data with the CWAI control, the control returns data as a Variant. You can pass most input parameters, such as device type and the number of scans, as Variants or longs.
  • DataSocket – DataSocket can handle Variants with internal representations of numeric types, strings, arrays, dates, and currency.
  • Analysis – Analysis functions accept Variants of almost any numerical type. If you are passing a single Variant to a ComponentWorks analysis function for processing, such as SubsetArray or IndexArray, the function returns the Variant with the same internal representation as you passed in. When you pass two or more Variant arrays to an analysis function, the function coerces the type as needed to perform the operation and returns the result as a Variant array of doubles. For example, if you pass an array of doubles and an array of longs as Variants to the CWArray.AddArray function, the function adds the two arrays and returns an array containing doubles.

Note The CWArray.BuildArray function requires that the elements of all input arrays have the same internal representation. If the arrays have different internal representations, call the CWArray.CopyArray function to duplicate the arrays. The CopyArray function returns the Variant as an array of doubles. Then pass the copied Variants to the BuildArray function.

How Do I Determine the Internal Representation of Variant Variables?


Although you rarely need to identify the internal representation of a Variant, you can determine the type within a Variant using the VarType or TypeName functions. Both of these Visual Basic functions return the type of the Variant, but TypeName returns the type as a string and VarType returns the type as an integer.

If you debug and you want to find the type of a Variant, you might find TypeName more useful. If you make decisions from your program based on the internal representation of the Variant, consider using the VarType function because it is more efficient at handling integers than strings.

Note Most ComponentWorks methods and events return data as Variants with an internal representation of a double or an array of double.

Note Refer to the MSDN Library for information about using these functions.

How Can I Manipulate or Convert Variant Data to a Specific Visual Basic Data Type?


Visual Basic offers the following group of functions to help you verify the internal representation of a Variant. For example, you might use the IsNumeric function to determine if a Variant variable contains a value that can be considered a valid numeric value or the IsDate function to determine if a Variant contains a value that can be considered a valid Date/Time value.

Visual Basic Function

Determines if the internal representation…

IsArray

is an array

IsDate

is a date

IsEmpty

is initialized or explicitely set to empty

IsNull

contains no valid data

IsNumeric

is evaluated as a number

IsObject

is an object variable

Once you have determined the internal representation of the Variant, you might want to convert the Variant and store it as a specific type. For example, suppose you use the CWNumEdit control to display a measurement. The control stores the value with an internal representation as a double. If you need the value to be stored and handled as an integer, use the CInt function to convert the double to an integer before performing any calculations so that your program performs integer math.

The following table lists other Visual Basic conversion functions:

Visual Basic Conversion Function

Converts Variant data to this type...

CBool

Boolean

CByte

Byte

CCur

Currency

CDate

Date

CDbl

Double

CInt

Integer

CLng

Long

CSng

Single

CStr

String

Note If you want to convert a typed variable to a Variant, use the Visual Basic CVar function. Refer to the MSDN Library for information about using CVar and other Visual Basic functions.

原创粉丝点击