Top Banner
Java2C# Antonio Cisternino Part III
40

Java2C# Antonio Cisternino Part III. Outline Classes Fields Properties virtual methods new names operator overloading Reflection Custom attributes.

Dec 26, 2015

Download

Documents

Matilda Barton
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

Java2C#

Antonio Cisternino

Part III

Page 2: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

Outline

Classes Fields Properties virtual methods new names operator overloading

Reflection Custom attributes Generation of code using reflection

Statements and other new operators

Page 3: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

Outline

Classes Fields Properties virtual methods new names operator overloading

Reflection Custom attributes Generation of code using reflection

Statements and other new operators

Page 4: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

Class Type

Classes are similar to Java and C++ classes: A class combines a state (fields) and behavior

(methods and properties) Instances are allocated onto heap Instance creation relies on constructors Garbage collector locates unreferenced objects and

invokes finalization method on them Access control to class members is controlled by the

execution engine With the exception of virtual methods the

elements of classes can be used also in structs!

Page 5: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

Class Fields

Objects’ state is kept into fields Each field has a type Example:

public class BufferedLog { private string[] buffer; private int size; //…}

Fields are eventually accessible through dot notation (object.field)

Page 6: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

Class Properties

Classes may expose values as properties Prop. comes from component systems (COM, …) and

are a way to access values inside components A property is referred from outside like a field although

accessing a property corresponds a method invocation Each property may define two methods: a getter and a

setter If the property is referenced as a value the getter is

invoked, otherwise the setter is called CLR reserves get_XXX and set_XXX method names

(with additional flags) to represents properties

Page 7: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

Properties

Properties are sort of operator “field access” overloading Properties are a useful abstraction to identify the get/set

methods typically used in Java Properties are defined with a get and a set block A property could be read-only, write-only or both The keyword value indicates the input parameter to the

setter Properties can be used to expose fields as well as

derived values from fields

Page 8: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

Properties: an example

public class Properties { private string name; public string Name { get { return name; } set { name = value; } } public string TName { get { return "Dr. " + name; } } public static void Main(string[] args) { Properties p = new Properties(); p.name = "Antonio Cisternino"; // Compilation error p.Name = "Antonio Cisternino"; // Invoke set Console.WriteLine(p.Name); Console.WriteLine(p.TName); p.TName = "Antonio Cisternino"; // Compilation error }}

Page 9: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

Methods

C# methods are similar to Java ones although C# offers a more comprehensive set of options to the programmer

C# allows controlling the method call using virtual keyword

Parameters passing can be controlled using out/ref/params keywords

Remote method invocation of methods can be improved if these specifiers are used

Page 10: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

Virtual methods

In compiled OO languages there is the problem of linking method calls on objects whose classes are in a hierarchy tree

In the following code:string s = "Test";object o = s; // Upcasting// String.ToString() is invokedreturn o.ToString();

At compile time it is unknown which is the real type of the object referenced by o

The programmer whishes that the invoked method is the one defined in the actual type (if present)

Page 11: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

Virtual methods

Each object holds a pointer to the vtable, a table of pointer to virtual methods of its type

In Java all the methods are virtual C# leaves the choice to the programmer if a method

should be considered virtual or not By default methods aren’t virtual When a type defines a method designed to be redefined

by inheritance must specify the virtual keyword Derived classes should use override keyword to indicate

that they are redefining an inherited method

Page 12: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

Virtual methods implementation

Object’s state

Type descriptor

Met

hods

Cost of virtual method invocation: two indirections

Page 13: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

Virtual methods example

public class VirtualTest { public virtual string Foo() { return "Foo"; } public string Foo2() { return "Foo2"; }}public class Derived : VirtualTest { public override string Foo() { return "DFoo"; } public string Foo2() { return "DFoo2"; }}public class MainClass { public static void Main(string[] args) { Derived d = new Derived(); VirtualTest v = d; // Output: DFoo Foo2 Console.WriteLine("{0}\t{1}", v.Foo(), v.Foo2()); // Output: DFoo DFoo2 Console.WriteLine("{0}\t{1}", f.Foo(), f.Foo2()); }}

This is not allowed! Name overriding must be explicit!

Page 14: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

Managing names

To avoid errors due to overriding of non-virtual methods C# requires that the new keyword is used when a method is defined

The rationale is “I want to reuse the same name used in the base class but this method is completely unrelated to the one inherited!”

Example: public new string Foo2() { ... }

C# supports also name management to resolve ambiguities when a type implements multiple interfaces

Page 15: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

Parameters declaration

Parameters to methods can be label to control the semantics of passing

By default the semantics is the same used by Java: pass by value

The modifiers allowed are:outrefparams

Page 16: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

Example

public void Foo(out int j, ref int k, params int[] rest) { … }

An out parameter can be uninitialized and should be assigned within method body

When ref is specified the annotated parameter is passed by reference: the value passed by the caller is modified

Params indicates that the compiler is allowed to transform a list of parameters into an array:Foo(out v, ref h, 1, 2, 3); -> Foo(out v, ref h, new int[]{1,2,3});

Page 17: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

Operators

C# borrows from C++ operator overloading A type can define a static method with a special name

that overloads an operator (i.e. +, -, …) Unary operators that can be overloaded are: +, -, !, ~, +

+, --, true, false Binary operators that can be overloaded are: +, -, *, /, %,

&, |, ^, <<, >>, ==, !=, >, <, >=, <= Cast operators can be overloaded Element access [] isn’t considered an operator! Non overridable operators: =, &&, ||, ?:, new, typeof,

sizeof

Page 18: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

Struct complex

struct Complex { private double re, im; public Complex(double r, double i) { re = r; im = i; } public static explicit operator double(Complex c) { return c.re; } public static Complex operator-(Complex c) { return new Complex(-c.re, -c.im); } public static Complex operator+(Complex c, Complex d) { return new Complex(c.re + d.re, c.im + d.im); } public static Complex operator+(Complex c, double d) { return new Complex(c.re + d, c.im); } public override string ToString() { return re + "+" + im + "i"; } }

Page 19: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

Example of use

public class MainClass { public static void Main(string[] args) { Complex c = new Complex(2, 3); Console.WriteLine("{0} + 1 = {1}", c, c + 1); Console.WriteLine("{0} + {0} + 1 = {1}", c, c + c + 1); Console.WriteLine("Re({0}) = {1}", c, (double)c); Console.WriteLine("-({0}) = {1}", c, -c); } } Output:

2+3i + 1 = 3+3i2+3i + 2+3i + 1 = 5+6iRe(2+3i) = 2-(2+3i) = -2+-3i

Page 20: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

Indexers

Indexers are sort of overloading of operator [] Through indexers a type may expose an array-

like notation to access data Indexer arguments may have any type as

parameter Indexers are allowed to have multiple

parameters Using indexers it is possible to expose

“functional access” to an object (i.e. hashtable)

Page 21: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

Example

class Vector { private object[] store = new object[10]; public object this[int i] { get { return store[i]; } set { if (i >= store.Length) { object[] o = new object[i + 10]; store.CopyTo(o, 0); store = o; } store[i] = value; }}}public class MainClass { public static void Main(string[] args) { Vector v = new Vector(); v[2] = "Ciao"; Console.WriteLine(v[2]); }}

Page 22: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

Outline

Classes Fields Properties virtual methods new names operator overloading

Reflection Custom attributes Generation of code using reflection

Statements and other new operators

Page 23: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

Reflection

Reflection is the ability of a program of access to a description of itself

A system may support reflection at different levels: from simple information on types (C++ RTTI) to reflecting the entire structure of the program

Another dimension of reflection is if a program is allowed to read or change itself

Introspection is the ability of a program to read information about itself

Intercession is the ability of a program to modify its own state through the description of itself

Page 24: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

Reflection

Support for reflection imposes an overhead, at least in space: a program must carry a representation of itself

Depending on information grain the overhead could be relevant

CLR supports reflection (both introspection and intercession) at type-system level

A program may inspect the structure of types in terms of fields, methods and so on

The program cannot access the IL code (it isn’t the source program anymore)

Page 25: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

CLI = Data + Metadata

CLI files contain definition of types annotated with their description (metadata)

Metadata are static and cannot be changed at runtime thus the only overhead is in terms of space

Metadata are crucial to support dynamic loading as well as other core services (i.e. remoting, reflection, and so on)

A program can access metadata using the reflection API The entry point to metadata is represented by

System.Type class Reflection types only exposed as CLR objects!

Page 26: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

Example

void printMethods(object o) { Type t = o.GetType(); Console.WriteLine("Methods of type {0}:", t.Name);

MethodInfo[] m = t.GetMethods(); for (int i = 0; i < m.Length; i++) { Console.WriteLine("Method {0}", m[i].Name); Console.WriteLine(m.ReturnType.Name); Console.WriteLine(m.GetParameters().Length); }}

Page 27: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

Reflection structure

Assembly

Type

ModuleMethodInfo

PropertyInfo

FieldInfo

MethodInfo

EventInfo

ConstructorInfo

ParameterInfo

o.GetType()typeof()

Page 28: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

Extending metadata

Metadata are organized as a graph CLR (and C#) allows to extend metadata with custom

information The abstraction provided are custom attributes Each element of the type system can be labeled with

attributes These attributes are attached to metadata and can be

searched using Reflection API Programmer can annotate a program with these

information and another program can exploit that to manage it

Example of use: Web services, Terrarium, Sort of MTS…

Page 29: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

C# and custom attributes

C# allows custom attributes to be specified using a special syntax:[WebMethod]public int Add(int i, int j) { return i + j;}

Web Method is a custom attribute on the method Add

Attributes can be specified on all elements (assemblies, modules, methods, fields, parameters, return types, …)

Page 30: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

How attributes work?

A custom attribute is an object of a class that inherits from System.Attribute (i.e. WebMethodAttribute)

Note that if the name of attribute type contains Attribute at the end this can be omitted!

When a custom attribute is used a new instance of the type is created, the program can specify the arguments to be passed to the constructor

Example of attribute type:class MyAttribute : System.Attribute { public string Foo; public MyAttribute(string f) { Foo = f; } public MyAttribute() { Foo = f; } }

Page 31: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

Use of MyAttribute

Example:[My] public class Foo { [My("Method")] public void Baz([My]int i) { }}

Reflection is used to access custom attributes:Console.WriteLine((MyAttribute)(typeof(Foo).GetCustomAttributes()[0]).Foo);

There are “meta-attributes” to specify how an attribute should be used and C# performs checks at compile time

Custom attribute are a way to support elements of declarative programming into C#

Page 32: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

Outline

Classes Fields Properties virtual methods new names operator overloading

Reflection Custom attributes Generation of code using reflection

Statements and other new operators

Page 33: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

Statements and new operators

Statements are essentially the same as Java C# introduces four new statements: foreach,

checked, lock and using It introduces also is, typeof and as operators to

deal with types Fall-through is forbidden within switch statement The new statements relies on standard

interfaces to work properly

Page 34: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

foreach

This statement allows iterating over a collection of objects

A type C is considered a collection type if either implements System.IEnumerable or satisfies the following conditions: C contains a public instance method with the signature

GetEnumerator() that returns a struct-type, class-type, or interface-type, which is called E in the following text.

E contains a public instance method with the signature MoveNext() and the return type bool.

E contains a public instance property named Current that permits reading the current value. The type of this property is said to be the element type of the collection type

Page 35: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

foreach example

object[] a = new int[]{ 1, 2, 3, 4 };foreach (int i in a) { Console.WriteLine(i);} The statement allocates a local variable called i

and uses the enumeration methods to iterate over the collection assignign to that variable the current value

An implicit cast is performed to the type used for the local variable

Page 36: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

checked/unchecked

With checked and unchecked keywords the program can control the behavior of the arithmetic operations

They are both expressions:checked(expr)unchecked(expr)

The keywords can be used also as statements to mark blocks: checked {…}

Page 37: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

lock

lock(x) is a shorthand for:System.Threading.Monitor.Enter(x);

try {

...

} finally {

System.Threading.Monitor.Exit(x);

} x must be an expression with reference type

Page 38: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

using

using(R r1 = new R()) { r1.F(); } is equivalent to:R r1 = new R(); try { r1.F();} finally { if (r1 != null) ((IDisposable)r1).Dispose(); }

This is possible because of IDisposable!

Page 39: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

typeof, is, as

There are operators to work with types: typeof returns the Type object of a given class:

Type t = typeof(string); is is a boolean operator to test if a reference can be

casted to a given type:if (t is object) { … }

as allow to perform a type cast that can fail:string s = o as string;if (s == null) Console.WriteLine("Not a string");

Page 40: Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.

Next lecture

Exception handling (no throws clause) Introduction to BCL Advanced features:

"preprocessor“ unsafe code interoperability:

using C++ using COM Interop tlbimp/tlbexp using PInvoke