Docstoc

PowerPoint Slides (PowerPoint download)

Document Sample
PowerPoint Slides (PowerPoint download) Powered By Docstoc
					                                                                                                                    1




Programming in C#.NET




         ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                        2




                  Lecture 7 – C# Basics VII

Outline
1.   Custom Attributes
2.   Reflection




                             ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                            3

          Custom Attributes

StructLayout




                 ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                             4

       Writing Custom Attributes

[FieldName("SocialSecurityNumber")]
public string SocialSecurityNumber
{
get {
// etc.

[FieldNameAttribute("SocialSecurity
  Number")]
public string SocialSecurityNumber
{
get {
// etc.
                  ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                   5

          Writing Custom Attributes

• The types of program elements to which the
  attribute can be applied (classes, structs,
  properties, methods, and so on).
• Whether it is legal for the attribute to be
  applied more than once to the same program
  element.
• Whether the attribute, when applied to a class
  or interface, is inherited by derived classes and
  interfaces.
• The mandatory and optional parameters the
  attribute takes.
                        ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                             6

       Writing Custom Attributes

[AttributeUsage(AttributeTargets.Pr
  operty,
AllowMultiple=false,
Inherited=false)]
public class FieldNameAttribute :
  Attribute
{
private string name;
public FieldNameAttribute(string
  name)
{
this.name = name;
}
}                 ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                             7

       Writing Custom Attributes

[AttributeUsage(AttributeTargets.Pr
  operty,
AllowMultiple=false,
Inherited=false)]
public class FieldNameAttribute :
  Attribute
{
private string name;
public FieldNameAttribute(string
  name)
{
this.name = name;
}
}                 ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                  8

             AttributeUsage attribute

•   All                        • GenericParameter
•   Assembly                     (.NET 2.0 only)
•   Class                      • Interface
•   Constructor                • Method
•   Delegate                   • Module
•   Enum                       • Parameter
•   Event                      • Property
•   Field                      • ReturnValue
                               • Struct




                       ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                             9

       Writing Custom Attributes

[assembly:SomeAssemblyAttribute(Par
  ameters)]
[module:SomeAssemblyAttribute(Param
  eters)]

[AttributeUsage(AttributeTargets.Pr
  operty | AttributeTargets.Field,
  AllowMultiple=false,
  Inherited=false)]
public class FieldNameAttribute :
  Attribute


                  ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                10

          Writing Custom Attributes

[FieldName("SocialSecurityNumber")]
[FieldName("NationalInsuranceNumber
  ")]
public string SocialSecurityNumber
{

// etc.




                     ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                              11

     Specifying attribute parameters

[FieldName("SocialSecurityNumber")]
public string SocialSecurityNumber
{

// etc.




                   ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                              12

 Specifying optional attribute parameters

  [FieldName("SocialSecurityNumber",
   Comment="This is the primary key
   field")]
public string SocialSecurityNumber
{

   // etc.




                   ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                     13

  Specifying optional attribute parameters
[AttributeUsage(AttributeTargets.Property,
   AllowMultiple=false,
   Inherited=false)]
public class FieldNameAttribute : Attribute
{
private string comment;
public string Comment
{
get
{
return comment;
}
set
{
comment = value;
}
}

// etc.
                          ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                 14
         Custom Attribute Example:
           WhatsNewAttributes
• The WhatsNewAttributes assembly, which
  contains the definitions of the attributes
• The VectorClass assembly, which contains
  the code to which the attributes have been
  applied
• The LookUpWhatsNew assembly, which
  contains the project that displays details of
  items that have changed




                      ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                 15

 The WhatsNewAttributes library assembly

• csc /target:library WhatsNewAttributes.cs




                      ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                                 16

  The WhatsNewAttributes library assembly
using System;

namespace Wrox.ProCSharp.WhatsNewAttributes
{
[AttributeUsage(
AttributeTargets.Class | AttributeTargets.Method,
AllowMultiple=true, Inherited=false)]
public class LastModifiedAttribute : Attribute
{
private DateTime dateModified;
private string changes;
private string issues;

public LastModifiedAttribute(string dateModified, string changes)
{
this.dateModified = DateTime.Parse(dateModified);
this.changes = changes;
}
public DateTime DateModified
{
get
{
return dateModified;
}
}




                                      ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                                 17

  The WhatsNewAttributes library assembly
public string Changes
{
get
{
return changes;
}
}

public string Issues
{
get
{
return issues;
}
set
{
issues = value;
}
}
}

[AttributeUsage(AttributeTargets.Assembly)]
public class SupportsWhatsNewAttribute : Attribute
{
}
}



                                      ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                            18

       The VectorClass assembly

using System;
using
  Wrox.ProCSharp.WhatsNewAttributes;
using System.Collections;
using System.Text;
[assembly: SupportsWhatsNew]




                 ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                            19

              The VectorClass assembly
namespace Wrox.ProCSharp.VectorClass
{
[LastModified("14 Feb 2002", "IEnumerable interface implemented " +
"So Vector can now be treated as a collection")]
[LastModified("10 Feb 2002", "IFormattable interface implemented " +
"So Vector now responds to format specifiers N and VE")]
class Vector : IFormattable, IEnumerable
{
      public double x, y, z;

      public Vector(double x, double y, double z)
      {
         this.x = x;
         this.y = y;
         this.z = z;
      }

[LastModified("10 Feb 2002",
"Method added in order to provide formatting support")]
public string ToString(string format, IFormatProvider formatProvider)
      {
         if (format == null)
            return ToString();


                                 ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                            20

       The VectorClass assembly

csc /target:library
  /reference:WhatsNewAttributes.dll
  VectorClass.cs




                 ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                            21

              Reflection

System.Type

System.Reflection.Assembly




                 ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                            22

        The System.Type Class

Type t = typeof(double);




                 ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                           23

               The System.Type Class

• You can use the C# typeof operator as in the preceding
  code. This operator takes the name of the type (not in
  quote marks, however) as a parameter.
• You can use the GetType() method, which all classes
  inherit from System.Object:
   double d = 10; Type t = d.GetType();
   GetType()is called against a variable, rather than taking the
     name of a type. Note, however, that the Type object returned is
     still associated with only that data type. It does not contain any
     information that relates to that instance of the type. The
     GetType() method can be useful if you have a reference to an
     object, but are not sure what class that object is actually an
     instance of.
• You can call the static method of the Type class,
  GetType():
   Type t = Type.GetType("System.Double");
                                ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                       24

                  Type properties

• Name
  – The name of the data type
• FullName
  – The fully qualified name of the data type (including the
    namespace name)
• Namespace
  – The name of the namespace in which the data type is
    defined




                            ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                      25

                  Type properties

• BaseType
  – Immediate base type of this type
• UnderlyingSystemType
  – The type that this type maps to in the .NET runtime
    (recall that certain .NET base types actually map to
    specific predefined types recognized by IL)




                           ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                  26

                Type properties

• IsAbstract,
• IsArray,
• IsClass,
• IsEnum,
• IsInterface,
• IsPointer,
• IsPrimitive (one of the predefined primitive
  data types),
• IsPublic,
• IsSealed,
• and IsValueType.
                       ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                              27

             Type properties

Type intType = typeof(int);
Console.WriteLine(intType.IsAbstract
  // writes false
Console.WriteLine(intType.IsClass
  // writes false
Console.WriteLine(intType.IsEnum
  // writes false
Console.WriteLine(intType.IsPrimitive
  // writes true
Console.WriteLine(intType.IsValueType
  // writes true

.

                   ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                              28

             Type properties

Type vecType = typeof(Vector);
  Console.WriteLine(vecType.IsAbstract);
// writes false
  Console.WriteLine(vecType.IsClass);
// writes true
  Console.WriteLine(vecType.IsEnum);
// writes false
  Console.WriteLine(vecType.IsPrimitive);
// writes false
  Console.WriteLine(vecType.IsValueType);
// writes false


                   ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                            29

           Type properties

Type t = typeof (Vector);
Assembly containingAssembly = new
  Assembly(t);




                 ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                           30

              Methods

Type t = typeof(double);
MethodInfo[] methods =
  t.GetMethods();
foreach (MethodInfo nextMethod in
  methods)
{

// etc.



                ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                              31

                Methods

ConstructorInfo
 GetConstructor(), GetConstructors()
EventInfo
 GetEvent(), GetEvents()
FieldInfo
 GetField(), GetFields()
InterfaceInfo
 GetInterface(), GetInterfaces()
MemberInfo
 GetMember(), GetMembers()
MethodInfo
 GetMethod(), GetMethods()
PropertyInfo
 GetProperty(), GetProperties()
                   ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                   32

The TypeView Example




        ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                             33

          The TypeView Example

using   System;
using   System.Text;
using   System.Windows.Forms;
using   System.Reflection;




                  ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                  34

           The TypeView Example

class MainClass
{
static void Main()
{
// modify this line to retrieve details of any
// other data type
Type t = typeof(double);

AnalyzeType(t);
MessageBox.Show(OutputText.ToString(), "Analysis
  of type "
+ t.Name);
Console.ReadLine();
}


                       ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                        35

              The TypeView Example
static void AnalyzeType(Type t)
{
AddToOutput("Type Name: " + t.Name);
AddToOutput("Full Name: " + t.FullName);
AddToOutput("Namespace: " + t.Namespace);
Type tBase = t.BaseType;
if (tBase != null)
AddToOutput("Base Type:" + tBase.Name);
Type tUnderlyingSystem = t.UnderlyingSystemType;
if (tUnderlyingSystem != null)
AddToOutput("UnderlyingSystem Type:" + tUnderlyingSystem.Name);

AddToOutput("\nPUBLIC MEMBERS:");
MemberInfo [] Members = t.GetMembers();
foreach (MemberInfo NextMember in Members)
{
AddToOutput(NextMember.DeclaringType + " " +
NextMember.MemberType + " " + NextMember.Name);
}
}


                             ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                            36

        The TypeView Example

static void AddToOutput(string Text)
{
OutputText.Append("\n" + Text);
}

csc
  /reference:System.Windows.Forms.dl
  l TypeView.cs



                 ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                            37

         The Assembly Class

Assembly assembly1 =
  Assembly.Load("SomeAssembly");
Assembly assembly2 =
  Assembly.LoadFrom
(@"C:\My
  Projects\Software\SomeOtherAssembl
  y");

string name = assembly1.FullName;


                 ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                              38
  Finding out about types defined in an
                assembly
Type[] types =
  theAssembly.GetTypes();
foreach(Type definedType in types)
{
DoSomethingWith(definedType);
}




                   ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                              39

   Finding out about custom attributes

Attribute[] definedAttributes =
Attribute.GetCustomAttributes(assem
  bly1);
// assembly1 is an Assembly object

Attribute supportsAttribute =
Attribute.GetCustomAttributes(assem
  bly1,
typeof(SupportsWhatsNewAttribute));


                   ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                40
   Completing the WhatsNewAttributes
                Example
csc /reference:WhatsNewAttributes.dll
  /reference:VectorClass.dll
  LookUpWhatsNew.cs

using   System;
using   System.Reflection;
using   System.Windows.Forms;
using   System.Text;
using   Wrox.ProCSharp.VectorClass;
using   Wrox.ProCSharp.WhatsNewAttributes;

namespace Wrox.ProCSharp.LookUpWhatsNew
{
                     ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                     41
     Completing the WhatsNewAttributes
                  Example
class WhatsNewChecker
{
static StringBuilder outputText = new
   StringBuilder(1000);
static DateTime backDateTo = new DateTime(2002, 2, 1);

static void Main()
{
Assembly theAssembly = Assembly.Load("VectorClass");
Attribute supportsAttribute =
Attribute.GetCustomAttribute(
theAssembly, typeof(SupportsWhatsNewAttribute));
string Name = theAssembly.FullName;

AddToMessage("Assembly: " + Name);
if (supportsAttribute == null)




                          ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                  42
    Completing the WhatsNewAttributes
                 Example
{
AddToMessage(
"This assembly does not support WhatsNew
  attributes");
return;
}
else
AddToMessage("Defined Types:");

Type[] types = theAssembly.GetTypes();
foreach(Type definedType in types)
DisplayTypeInfo(theAssembly, definedType);

MessageBox.Show(outputText.ToString(),
"What\'s New since " + backDateTo.
Console.ReadLine();
}
                       ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                  43
    Completing the WhatsNewAttributes
                 Example
static void DisplayTypeInfo(Assembly theAssembly,
  Type type)
{
// make sure we only pick out classes
if (!(type.IsClass))
return;
AddToMessage("\nclass " + type.Name);

Attribute [] attribs =
  Attribute.GetCustomAttributes(type);
if (attribs.Length == 0)
AddToMessage("No changes to this class\n");
else
foreach (Attribute attrib in attribs)
WriteAttributeInfo(attrib);

MethodInfo [] methods = type.GetMethods();
                       ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                  44
    Completing the WhatsNewAttributes
                 Example
AddToMessage("CHANGES TO METHODS OF THIS CLASS:");
foreach (MethodInfo nextMethod in methods)
{
object [] attribs2 =
nextMethod.GetCustomAttributes(
typeof(LastModifiedAttribute), false);
if (attribs2 != null)
{
AddToMessage(
nextMethod.ReturnType + " " + nextMethod.Name +
  "()");
foreach (Attribute nextAttrib in attribs2)
WriteAttributeInfo(nextAttrib);
}
}
}

                       ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                        45
     Completing the WhatsNewAttributes
                  Example
static void WriteAttributeInfo(Attribute attrib)
{

LastModifiedAttribute lastModifiedAttrib =
attrib as LastModifiedAttribute;
if (lastModifiedAttrib == null)
return;

// check that date is in range
DateTime modifiedDate = lastModifiedAttrib.DateModified;
if (modifiedDate < backDateTo)
return;

AddToMessage(" MODIFIED: " +
modifiedDate.ToLongDateString() + ":");
AddToMessage("    " + lastModifiedAttrib.Changes);
if (lastModifiedAttrib.Issues != null)
AddToMessage("    Outstanding issues:" +
lastModifiedAttrib.Issues);
}


                             ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                             46
   Completing the WhatsNewAttributes
                Example
static void AddToMessage(string
  message)
{
outputText.Append("\n" + message);
}
}
}




                  ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                          47
Completing the WhatsNewAttributes
             Example




               ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                       48

                       Summary

• This chapter did not attempt to cover the entire topic of
  reflection. Reflection is an extensive subject worthy of a
  book of its own. Instead, it looked at the Type and
  Assembly classes, which are the primary entry points
  through which you can access the extensive capabilities
  provided by reflection.
• In addition, this chapter demonstrated a specific aspect
  of reflection that you are likely to use more often than
  any other — the inspection of custom attributes. You
  learned how to define and apply your own custom
  attributes, and how to retrieve information about
  custom attributes at runtime.


                            ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:3
posted:12/17/2011
language:
pages:48