Студопедия

Главная страница Случайная страница

КАТЕГОРИИ:

АвтомобилиАстрономияБиологияГеографияДом и садДругие языкиДругоеИнформатикаИсторияКультураЛитератураЛогикаМатематикаМедицинаМеталлургияМеханикаОбразованиеОхрана трудаПедагогикаПолитикаПравоПсихологияРелигияРиторикаСоциологияСпортСтроительствоТехнологияТуризмФизикаФилософияФинансыХимияЧерчениеЭкологияЭкономикаЭлектроника






Have to pay attention not to cross the boundaries.






Person[, ] racers2 = (Person[, ])racers;

Person first = racers2[1, 10]; Person last = racers2[2, 12];

 

41.Sorting arrays in C#.

Sorting array of primitive types

To sort array of primitive types such as int, double or string use method Array.Sort(Array) with the array as a paramater. The primitive types implements interface IComparable, which is internally used by the Sort method. Example:

1) // sort int array

int[] intArray = new int[5] { 8, 10, 2, 6, 3 };

Array.Sort(intArray);

// write array

foreach (int i in intArray) Console.Write(i + " "); // output: 2 3 6 8 10

2) // sort string array

string[] stringArray = new string[5] { " X", " B", " Z", " Y", " A" };

Array.Sort(stringArray);

// write array

foreach (string str in stringArray) Console.Write(str + " "); // output: A B X Y Z

 

Sorting array of custom type using delegate

To sort our own types or to sort by more sophisticated rules, we can use delegate to anonymous method. The generic delegate Comparison< T> is declared as public delegate int Comparison< T> (T x, T y). It points to a method that compares two objects of the same type. It should return less then 0 when X < Y, zero when X = Y and greater then 0 when X > Y. The method (to which the delegate points) can be also an anonymous method (written inline).

Sorting array using IComparable

If we implement IComparable interface in our custom type, we can sort array easily like in the case of primitive types. The Sort method calls internally IComparable.Com­pareTo method.

If we use custom classes with the array, we must implement the interface IComparable. This interface defines just one method, CompareTo(), that must return 0 if the objects to compare are equal, a value smaller than 0 if the instance should go before the object from the parameter, and a value larger than 0 if the instance should go after the object from the parameter.

42.Tuples in C#.

Arrays combine objects of the same type; tuples can combine objects of different types. Tuples have the origin in functional programming languages such as F# where they are used often. With.NET 4, tuples are available with the.NET Framework for all.NET languages.

.NET 4 defines eight generic Tuple classes and one static Tuple class that act as a factory of tuples. The different generic Tuple classes are here for supporting a different number of elements; e.g., Tuple< T1> contains one element, Tuple< T1, T2> contains two elements, and so on.

The method Divide() demonstrates returning a tuple with two members — Tuple< int, int>. The parameters of the generic class define the types of the members, which are both integers. The tuple is created with the static Create() method of the static Tuple class. Again, the generic parameters of the Create() method define the type of tuple that is instantiated. The newly created tuple is initialized with the result and reminder variables to return the result of the division:

public static Tuple< int, int> Divide(int dividend, int divisor)

{

int result = dividend / divisor;

int reminder = dividend % divisor;

return Tuple.Create< int, int> (result, reminder);

}

The following code shows invoking the Divide() method. The items of the tuple can be accessed with the

properties Item1 and Item2:

var result = Divide(5, 2);

Console.WriteLine(" result of division: {0}, reminder: {1}",

result.Item1, result.Item2);

The last template parameter is named TRest to indicate that you must pass a tuple itself. That way you can create tuples with any number of parameters.

To demonstrate this functionality: public class Tuple< T1, T2, T3, T4, T5, T6, T7, TRest> Here, the last template parameter is a tuple type itself, so you can create a tuple with any number of items:

var tuple = Tuple.Create< string, string, string, int, int, int, double,

Tuple< int, int> > (" Stephanie", " Alina", " Nagel", 2009, 6, 2, 1.37,

Tuple.Create< int, int> (52, 3490));

43.Operators in C#.

 

Category Operator

 

Arithmetic + – * / %
Logical & | ^ ~ & & ||!
String concatenation +
Increment and decrement ++ ––
Bit shifting < < > >
Comparison ==! = < > < = > =
Assignment = += -= *= /= %= & = |= ^= < < = > > =
Member access (for objects and structs) .
Indexing (for arrays and indexers) []
Cast ()
Conditional (the ternary operator) ?:
Delegate concatenation and removal + -  
Object creation new
Type information size of is type of as
Overflow exception control checked unchecked
Indirection and address []
Namespace alias qualifier ::
Null coalescing operator ??

 

The Namespace Alias Qualifier in C# lets developers use the alias name instead of the complete namespace name. The advantage of the Namespace Alias Qualifier is that it lets us use the alias name instead of a bigger namespace and it also helps to avoid the ambiguous definitions of the classes.

Null coalescing operator, specified with the "?? " characters, has shorter source code and is equivalent to testing for null.

 

44.Type conversions in C#.

With the List< T> method ConvertAll< TOutput> (), all types of a collection can be converted to a different type. The ConvertAll< TOutput> () method uses a Converter delegate that is defined like this: public sealed delegate TOutput Converter< TInput, TOutput> (TInput from);

The generic types TInput and TOutput are used with the conversion. TInput is the argument of the delegate method, and TOutput is the return type.

In this example, all Racer types should be converted to Person types. Whereas the Racer type contains a firstName, lastName, country, and the number of wins, the Person type contains just a name. For the conversion, the country of the racer and race wins can be ignored, but the name must be converted:

public class Person

{ private string name;

public Person(string name)

{ this.name = name;

}

public override string ToString()

{ return name;

}

}

 

The conversion happens by invoking the racers.ConvertAll < Person > () method. The argument of this method is defined as a Lambda expression with an argument of type Racer and a Person type that is returned. In the implementation of the Lambda expression, a new Person object is created and returned. For the Person object, the FirstName and LastName are passed to the constructor:

List < Person > persons =

racers. ConvertAll < Person > (

r = > new Person(r.FirstName + " " + r.LastName));

The result of the conversion is a list containing the converted Person objects: persons of type

List < Person >.

45.Comparing reference types for equality in C#.

System.Object defines three different methods for comparing objects

for equality: ReferenceEquals() and two versions of Equals(). Add to this the comparison operator (==), and there actually four ways of comparing for equality. Some subtle differences exist between the different methods:

The referenceequals() Method

ReferenceEquals() is a static method that tests whether two references refer to the same instance of a class, specifically whether the two references contain the same address in memory.

ReferenceEquals() will always return true if supplied with two references that refer to the same object instance, and false otherwise. It does, however, consider null to be equal to null:

SomeClass x, y;

x = new SomeClass();

y = new SomeClass();

bool B1 = ReferenceEquals(null, null); // returns true

bool B2 = ReferenceEquals(null, x); // returns false

bool B3 = ReferenceEquals(x, y); // returns false because x and y

// point to different objects

The virtual equals() Method

The System.Object implementation of the virtual version of Equals() also works by comparing references. However, because this method is virtual, we can override it in our own classes to compare objects by value. In particular, if we intend instances of our class to be used as keys in a dictionary, we will need to override this method to compare values.

The static equals() Method

The static version of Equals() actually does the same thing as the virtual instance version. The difference

is that the static version takes two parameters and compares them for equality.

Comparison operator (==). The comparison operator an intermediate option between strict value comparison and strict reference comparison. In most cases, writing the following means that we are comparing references: bool b = (x == y); // x, y object references

46.Operator overloading in C#.

Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator being defined. Like any other function, an overloaded operator has a return type and a parameter list.

For example:

public static Box operator+ (Box b, Box c)

{

Box box = new Box();

box.length = b.length + c.length;

box.breadth = b.breadth + c.breadth;

box.height = b.height + c.height;

return box;

}

The above function implements the addition operator (+) for a user-defined class Box. It adds the attributes of two Box objects and returns the resultant Box object.

The overloading is not concerned just with arithmetic operators. We can also consider the comparison operators, ==, <, >,! =, > =, and < =. For example the statement if (a==b). For classes, this statement will, by default, compare the references a and b. It tests to see if the references point to the same location in memory, rather than checking to see if the instances actually contain the same data. For the string class, this behavior is overridden so that comparing strings really does compare the contents of each string. For structs, the == operator does not do anything at all by default. Trying to compare two structs to see if they are equal produces a compilation error unless you explicitly overload == to tell the compiler how to perform the comparison.

Overloading the Conversion operators. We might also need to implement conversion operators sometimes so that our type can safely be converted to and from other types. We can define the conversion operators as implicit or explicit. In case of implicit conversion the user will not have to explicitly type cast our type to target type and our conversion operation will work. In case of explicit conversion the user will have to explicitly cast our type to target type to invoke our conversion operation. If the casting is not performed it will give a compile time error.

47. Delegates in C#.

Delegates are the.NET version of addresses to methods. For example, each student on the final exams has the definite place. Student is the variable and the definite place is the link or address of this variable. You can call the method by its name and also you can call it by its delegate. Compare this to C++, where function pointers are nothing more than a pointer to a memory location that are not type - safe. You have no idea what a pointer is really pointing to, and items such as parameters and return types are not known. This is completely different with.NET; delegates are type - safe classes that define the return types and types of parameters. The delegate class not only contains a reference to a method, but can hold references to multiple methods. So, then you need to know how to declare it?! You have to start by defining the delegates you want to use. Defining delegates means telling the compiler what kind of method a delegate of that type will represent. Then, you have to create one or more instances of that delegate. Behind the scenes, the compiler creates a class that represents the delegate. The syntax for defining delegates looks like this:

delegate double MathAction(double num);

One good way of understanding delegates is by thinking of a delegate as something that gives a name to a method signature and the return type.

Delegates are implemented as classes derived from the class System.MulticastDelegate, which is derived from the base class System.Delegate. The C# compiler is aware of this class and uses its delegate syntax to shield you from the details of the operation of this

class. This is another good example of how C# works in conjunction with the base classes to make programming as easy as possible.

So, the following is the simple example of using the delegates:

delegate double MathAction(double num);

class DelegateTest

{ static double Double(double input)

{ return input * 2; }

static void Main()

{ MathAction ma = Double;

double multByTwo = ma(4.5);

Console.WriteLine(" multByTwo: {0}", multByTwo); }

// Output: multByTwo: 9 }

48.Lambda expressions in C#

Lambda expressions are directly related to delegates. When the parameter is a delegate type, you can use a Lambda expression to implement a method that ’ s referenced from the delegate. To create a lambda expression, you specify input parameters (if any) on the left side of the lambda operator =>, and you put the expression or statement block on the other side. For example, the lambda expression x => x * x specifies a parameter that’s named x and returns the value of x squared. You can assign this expression to a delegate type:

delegate int del(int i);

static void Main(string[] args)

{ del myDelegate = x => x * x;

int j = myDelegate(5); //j = 25}

With Lambda expressions there are several ways to define parameters. If there’s only one parameter, just the name of the parameter is enough.(x=> x*x). If a delegate uses more than one parameter, you can combine the parameter names inside brackets ((x, y)=> x*y).

If the Lambda expression consists of a single statement, a method block with curly brackets and a return statement is not needed. Func< double, double> square = x => x * x;

It’s completely legal to add curly brackets, a return statement, and semicolons. Usually it’s just easier to

read without: del square = x =>

{return x * x; }

However, if you need multiple statements in the implementation of the Lambda expression, curly bracketsand the return statement are required:

del lambda = param = >

{param += mid;

param += " and this was added to the string.";

return param; }.Here is the simple example of using lambda expressions:

delegate double MathAction(double num); class Mydelegate{ static void Main() { MathAction ma = s => s * s * s; double cube = ma(2.0); Console.WriteLine(" cube: {0}", cube); } // Output: cube: 8.0}

49. Events in C#

Events are based on delegates and offer a publish/subscribe mechanism to delegates. You can find events everywhere across the framework. In Windows applications, the Button class offers the Click event.

This type of event is a delegate. A handler method that is invoked when the Click event is fired needs to be defined, with the parameters as defined by the delegate type. So, events enable a class or object to notify other classes or objects when something of interest occurs. The class that sends (or raises) the event is called the publisher and the classes that receive (or handle) the event are called subscribers.

To declare an event inside a class, first a delegate type for the event must be declared, if none is already declared.

public delegate void Del (object sender, EventArgs e);

The delegate type defines the set of arguments that are passed to the method that handles the event. Multiple events can share the same delegate type, so this step is only necessary if no suitable delegate type has already been declared. Next, the event itself is declared.

public event ChangedEventHandler Changed;

An event is declared like a field of delegate type, except that the keyword event precedes the event declaration, following the modifiers. So, event publisher is the part of code that generates the events. Event listener is the part of code that process them. It’s usually a set of methods. And they communicate via delegates.

Here is the simple example of using events:

public class SampleEventArgs { public SampleEventArgs(string s) { Text = s; } public String Text {get; private set; } } public class Publisher { public delegate void SampleEventHandler(object sender, SampleEventArgs e); public event SampleEventHandler SampleEvent; protected virtual void RaiseSampleEvent() { if (SampleEvent! = null) SampleEvent(this, new SampleEventArgs(" Hello")); }}

50. System.String class in C#.

System.String is a class specifically designed to store a string and allow a large number of operations on the string. In addition, due to the importance of this data type, C# has its own keyword and associated

syntax to make it particularly easy to manipulate strings using this class.

You can concatenate strings using operator overloads:

string message1 = " Hello"; // returns " Hello"

message1 += ", There"; // returns " Hello, There"

string message2 = message1 + "! "; // returns " Hello, There! "

C# also allows extraction of a particular character using an indexer-like syntax: string message = " Hello";

char char4 = message[4]; // returns 'o'. Note the string is zero-indexed

This enables you to perform such common tasks as replacing characters, removing whitespace, and capitalization. System.String class has many standard methods like Compare, CompareTo, CopyTo, Format, Join, Equals and so on. For example, method CopyTo Copies a specific number of characters from the selected index to an entirely new

instance of an array. public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) Method Compare(string, string) Compares two specified String objects and returns an integer that indicates their relative position in the sort order. using System; public class Example{ public static void Main() { string s1 = " ani\u00ADmal"; string s2 = " animal"; Console.WriteLine(" Comparison of '{0}' and '{1}': {2}", s1, s2, String.Compare(s1, s2)); }}

51. System.Text.StringBuilder class in C#

The processing you can do on a StringBuilder is limited to substitutions and appending or removing text from strings. However, it works in

a much more efficient way. When you construct a string using the String class, just enough memory is allocated to hold the string. The

StringBuilder, however, normally allocates more memory than is actually needed. You, as a developer, have the option to indicate how much memory the StringBuilder should allocate, but if you do not, the

amount will default to some value that depends on the size of the string that the StringBuilder instance is initialized with. The StringBuilder class has two main properties:

➤ Length, which indicates the length of the string that it actually contains

➤ Capacity, which indicates the maximum length of the string in the memory allocation

Any modifications to the string take place within the block of memory assigned to the StringBuilder instance, which makes appending substrings and replacing individual characters within strings very efficient. Removing or inserting substrings is inevitably still inefficient because it means that the following part of the string has to be moved. Only if you perform some operation that exceeds the capacity of the string is it necessary to allocate new memory and possibly move the entire contained string. In adding extra capacity, based on our experiments the StringBuilder appears to double its capacity if it detects the capacity has been exceeded and no new value for the capacity has been set.

System.Text.StringBuilder class has the following methods: Append(), AppendFormat(), Insert(), Remove(), Replace(), ToString().

Here is the simple example of this class:

Using System;

Using System.Text;

{class Program

{static void Main (string[] args){

StringBuilder hello=new Stringbuilder (“hello I am student”, 120);

Hello.AppendFormat(“and IS is my specialty”); }}}

52. Format strings in C#

Format strings replaces each format item in a specified string with the text equivalent of a corresponding object's value. As you probably know, you need to specify the format in which you want a variable displayed when you call Console.WriteLine(). For example, if you want to display the value of a variable in a list box or text box, you will normally use the String.Format() method to obtain the appropriate string representation of the variable. However, the actual format specifiers you use to request a particular format are identical to those passed to Console.WriteLine(). In this example in Console.WriteLine() used format string:

double d = 13.45;

int i = 45;

Console.WriteLine(" The double is {0, 10: E} and the int contains {1}", d, i);

The format string itself consists mostly of the text to be displayed, but wherever there is a variable to be formatted, its index in the parameter list appears in braces. You might also include other information inside

the braces concerning the format of that item. For example, you can include:

-The number of characters to be occupied by the representation of the item, prefixed by a comma. A negative number indicates that the item should be left-justified, whereas a positive number indicates that it should be right-justified. If the item actually occupies more characters than have been requested, it will still appear in full.

- A format specifier, preceded by a colon. This indicates how you want the item to be formatted. For example, you can indicate whether you want a number to be formatted as a currency or displayed in

scientific notation.

 

 

53.Regular expressions in C#.

The regular expressions language is designed specifically for string processing. NET also offers some very sophisticated classes that deal withsituations in which you need to identify all words that begin with “ s ” and contain at least one “ n, ” or strings that adhere to an employee ID or a Social Security number construction. You can write methods to perform this kind of processing using the String class, such methods are cumbersome to write. Instead, you will find that some classes, specifically those from System.Text.RegularExpressions, are designed to perform this kind of processing.It contains two features:

1)A set of escape codes for identifying specific types of characters. You will be familiar with the use ofthe * character to represent any substring in DOS expressions. (For example, the DOS command

Dir Re* lists the files with names beginning with Re.) Regular expressions use many sequences likethis to represent items such as any one character, a word break, one optional character, and so on.

2)A system for grouping parts of substrings and intermediate results during a search operation.With regular expressions, you can perform quite sophisticated and high - level operations on strings. Forexample, you can:

-Identify all repeated words in a string

-Convert all words to title case

-Convert all words longer than three characters to title case

-Separate the various elements of a URI

The following table lists some of the main special characters or escape sequences that you can use.

symbol Meaning Expl Matches
^ Beginning of input text ^B B, but only if first character in text
$   End of input text X$ X, but only if last character in text
. Any single character except the newline character (\)   i.ation isation, ization

54. Lists in C#.

List < T > is a collection class that can be compared to arrays.

You can create list objects by invoking the default constructor. With the generic class List< T>, you must specify the type for the values of the list with the declaration. var intList = new List< int> ();

You can add elements to the list with the Add() method as shown. The generic instantiated type defines the parameter type of the Add() method.

var intList = new List < int > ();

intList.Add(1);

intList.Add(2);


Поделиться с друзьями:

mylektsii.su - Мои Лекции - 2015-2024 год. (0.032 сек.)Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав Пожаловаться на материал