Csharp/C Sharp/Class Interface/Class Method
Содержание
- 1 Add a method that takes two arguments
- 2 Add a method to Building
- 3 A simple example of recursion
- 4 A simple example that uses a parameter
- 5 Automatic type conversions can affect overloaded method resolution
- 6 Call class methods 2
- 7 C# Classes Member Functions
- 8 change field value in a method
- 9 Class a class method
- 10 Define methods that return a value and accept parameters
- 11 Demonstrate method overloading
- 12 Method Attributes
- 13 Method overloading test
- 14 Overloading Classes
- 15 Return an array
- 16 Use a class factory
Add a method that takes two arguments
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Add a method that takes two arguments.
using System;
class ChkNum {
// Return true if x is prime.
public bool isPrime(int x) {
for(int i=2; i < x/2 + 1; i++)
if((x %i) == 0) return false;
return true;
}
// Return the least common denominator.
public int lcd(int a, int b) {
int max;
if(isPrime(a) | isPrime(b)) return 1;
max = a < b ? a : b;
for(int i=2; i < max/2 + 1; i++)
if(((a%i) == 0) & ((b%i) == 0)) return i;
return 1;
}
}
public class ParmDemo1 {
public static void Main() {
ChkNum ob = new ChkNum();
int a, b;
for(int i=1; i < 10; i++)
if(ob.isPrime(i)) Console.WriteLine(i + " is prime.");
else Console.WriteLine(i + " is not prime.");
a = 7;
b = 8;
Console.WriteLine("Least common denominator for " +
a + " and " + b + " is " +
ob.lcd(a, b));
a = 100;
b = 8;
Console.WriteLine("Least common denominator for " +
a + " and " + b + " is " +
ob.lcd(a, b));
a = 100;
b = 75;
Console.WriteLine("Least common denominator for " +
a + " and " + b + " is " +
ob.lcd(a, b));
}
}
Add a method to Building
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Add a method to Building.
using System;
class Building {
public int floors; // number of floors
public int area; // total square footage of building
public int occupants; // number of occupants
// Display the area per person.
public void areaPerPerson() {
Console.WriteLine(" " + area / occupants +
" area per person");
}
}
// Use the areaPerPerson() method.
public class BuildingDemo2 {
public static void Main() {
Building house = new Building();
Building office = new Building();
// assign values to fields in house
house.occupants = 4;
house.area = 2500;
house.floors = 2;
// assign values to fields in office
office.occupants = 25;
office.area = 4200;
office.floors = 3;
Console.WriteLine("house has:\n " +
house.floors + " floors\n " +
house.occupants + " occupants\n " +
house.area + " total area");
house.areaPerPerson();
Console.WriteLine();
Console.WriteLine("office has:\n " +
office.floors + " floors\n " +
office.occupants + " occupants\n " +
office.area + " total area");
office.areaPerPerson();
}
}
A simple example of recursion
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// A simple example of recursion.
using System;
class Factorial {
// This is a recursive function.
public int factR(int n) {
int result;
if(n==1) return 1;
result = factR(n-1) * n;
return result;
}
// This is an iterative equivalent.
public int factI(int n) {
int t, result;
result = 1;
for(t=1; t <= n; t++) result *= t;
return result;
}
}
public class Recursion {
public static void Main() {
Factorial f = new Factorial();
Console.WriteLine("Factorials using recursive method.");
Console.WriteLine("Factorial of 3 is " + f.factR(3));
Console.WriteLine("Factorial of 4 is " + f.factR(4));
Console.WriteLine("Factorial of 5 is " + f.factR(5));
Console.WriteLine();
Console.WriteLine("Factorials using iterative method.");
Console.WriteLine("Factorial of 3 is " + f.factI(3));
Console.WriteLine("Factorial of 4 is " + f.factI(4));
Console.WriteLine("Factorial of 5 is " + f.factI(5));
}
}
A simple example that uses a parameter
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// A simple example that uses a parameter.
using System;
class ChkNum {
// Return true if x is prime.
public bool isPrime(int x) {
for(int i=2; i < x/2 + 1; i++)
if((x %i) == 0) return false;
return true;
}
}
public class ParmDemo {
public static void Main() {
ChkNum ob = new ChkNum();
for(int i=1; i < 10; i++)
if(ob.isPrime(i)) Console.WriteLine(i + " is prime.");
else Console.WriteLine(i + " is not prime.");
}
}
Automatic type conversions can affect overloaded method resolution
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
/* Automatic type conversions can affect
overloaded method resolution. */
using System;
class Overload2 {
public void f(int x) {
Console.WriteLine("Inside f(int): " + x);
}
public void f(double x) {
Console.WriteLine("Inside f(double): " + x);
}
}
public class TypeConv {
public static void Main() {
Overload2 ob = new Overload2();
int i = 10;
double d = 10.1;
byte b = 99;
short s = 10;
float f = 11.5F;
ob.f(i); // calls ob.f(int)
ob.f(d); // calls ob.f(double)
ob.f(b); // calls ob.f(int) -- type conversion
ob.f(s); // calls ob.f(int) -- type conversion
ob.f(f); // calls ob.f(double) -- type conversion
}
}
Call class methods 2
/*
Learning C#
by Jesse Liberty
Publisher: O"Reilly
ISBN: 0596003765
*/
using System;
public class MyTime1 {
// private member variables
int year;
int month;
int date;
int hour;
int minute;
int second;
// public method
public void DisplayCurrentTime()
{
System.Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}",
month, date, year, hour, minute, second);
}
// constructor
public MyTime1(int theYear, int theMonth, int theDate,
int theHour, int theMinute, int theSecond)
{
year = theYear;
month = theMonth;
date = theDate;
hour = theHour;
minute = theMinute;
second = theSecond;
}
static void Main()
{
MyTime1 timeObject = new MyTime1(2005,3,25,9,35,20);
timeObject.DisplayCurrentTime();
}
}
C# Classes Member Functions
using System;
public class MemberFunctions
{
public static void Main()
{
Point myPoint = new Point(10, 15);
Console.WriteLine("myPoint.X {0}", myPoint.GetX());
Console.WriteLine("myPoint.Y {0}", myPoint.GetY());
}
}
class Point
{
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
// accessor functions
public int GetX() {return(x);}
public int GetY() {return(y);}
// variables now private
int x;
int y;
}
change field value in a method
using System;
public class Foo
{
public int i;
}
class RefTest2App
{
public static void ChangeValue(Foo f)
{
f.i = 42;
}
static void Main(string[] args)
{
Foo test = new Foo();
test.i = 6;
Console.WriteLine("BEFORE METHOD CALL");
Console.WriteLine("test.i={0}", test.i);
Console.WriteLine();
ChangeValue(test);
Console.WriteLine("AFTER METHOD CALL");
Console.WriteLine("test.i={0}", test.i);
}
}
Class a class method
/*
Learning C#
by Jesse Liberty
Publisher: O"Reilly
ISBN: 0596003765
*/
using System;
class MyClass
{
public void SomeMethod(int firstParam, float secondParam)
{
Console.WriteLine(
"Here are the parameters received: {0}, {1}",
firstParam, secondParam);
}
}
public class Tester111
{
static void Main()
{
int howManyPeople = 5;
float pi = 3.14f;
MyClass mc = new MyClass();
mc.SomeMethod(howManyPeople, pi);
}
}
Define methods that return a value and accept parameters
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
Example5_3.cs illustrates how to define methods
that return a value and accept parameters
*/
// declare the Car class
class Car
{
public int yearBuilt;
public double maximumSpeed;
// the Age() method calculates and returns the
// age of the car in years
public int Age(int currentYear)
{
int age = currentYear - yearBuilt;
return age;
}
// the Distance() method calculates and returns the
// distance traveled by the car, given its initial speed,
// maximum speed, and time for the journey
// (assuming constant acceleration of the car)
public double Distance(double initialSpeed, double time)
{
return (initialSpeed + maximumSpeed) / 2 * time;
}
}
public class Example5_3
{
public static void Main()
{
// declare a Car object reference and
// create a Car object
System.Console.WriteLine("Creating a Car object and " +
"assigning its memory location to redPorsche");
Car redPorsche = new Car();
// assign values to the fields
redPorsche.yearBuilt = 2000;
redPorsche.maximumSpeed = 150;
// call the methods
int age = redPorsche.Age(2001);
System.Console.WriteLine("redPorsche is " + age + " year old.");
System.Console.WriteLine("redPorsche travels " +
redPorsche.Distance(31, .25) + " miles.");
}
}
Demonstrate method overloading
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Demonstrate method overloading.
using System;
class Overload {
public void ovlDemo() {
Console.WriteLine("No parameters");
}
// Overload ovlDemo for one integer parameter.
public void ovlDemo(int a) {
Console.WriteLine("One parameter: " + a);
}
// Overload ovlDemo for two integer parameters.
public int ovlDemo(int a, int b) {
Console.WriteLine("Two parameters: " + a + " " + b);
return a + b;
}
// Overload ovlDemo for two double parameters.
public double ovlDemo(double a, double b) {
Console.WriteLine("Two double parameters: " +
a + " "+ b);
return a + b;
}
}
public class OverloadDemo {
public static void Main() {
Overload ob = new Overload();
int resI;
double resD;
// call all versions of ovlDemo()
ob.ovlDemo();
Console.WriteLine();
ob.ovlDemo(2);
Console.WriteLine();
resI = ob.ovlDemo(4, 6);
Console.WriteLine("Result of ob.ovlDemo(4, 6): " +
resI);
Console.WriteLine();
resD = ob.ovlDemo(1.1, 2.32);
Console.WriteLine("Result of ob.ovlDemo(1.1, 2.2): " +
resD);
}
}
Method Attributes
using System;
using System.Reflection;
public class TransactionableAttribute : Attribute {
public TransactionableAttribute() {
}
}
class SomeClass {
[Transactionable]
public void Foo() { }
public void Bar() { }
[Transactionable]
public void Goo() { }
}
class Test {
[STAThread]
static void Main(string[] args) {
Type type = Type.GetType("SomeClass");
foreach (MethodInfo method in type.GetMethods()) {
foreach (Attribute attr in
method.GetCustomAttributes(true)) {
if (attr is TransactionableAttribute) {
Console.WriteLine(method.Name);
}
}
}
}
}
Method overloading test
/*
Learning C#
by Jesse Liberty
Publisher: O"Reilly
ISBN: 0596003765
*/
using System;
namespace MethodOverloading
{
public class Time1
{
// private member variables
private int Year;
private int Month;
private int Date;
private int Hour;
private int Minute;
private int Second;
// public accessor methods
public void DisplayCurrentTime()
{
System.Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}",
Month, Date, Year, Hour, Minute, Second);
}
// constructors
public Time1(System.DateTime dt)
{
Year = dt.Year;
Month = dt.Month;
Date = dt.Day;
Hour = dt.Hour;
Minute = dt.Minute;
Second = dt.Second;
}
public Time1(int Year, int Month, int Date,
int Hour, int Minute, int Second)
{
this.Year = Year;
this.Month = Month;
this.Date = Date;
this.Hour = Hour;
this.Minute = Minute;
this.Second = Second;
}
}
public class MethodOverloadingTester
{
public void Run()
{
System.DateTime currentTime = System.DateTime.Now;
Time1 time1 = new Time1(currentTime);
time1.DisplayCurrentTime();
Time1 time2 = new Time1(2000,11,18,11,03,30);
time2.DisplayCurrentTime();
}
static void Main()
{
MethodOverloadingTester t = new MethodOverloadingTester();
t.Run();
}
}
}
Overloading Classes
/*
* C# Programmers Pocket Consultant
* Author: Gregory S. MacBeth
* Email: gmacbeth@comporium.net
* Create Date: June 27, 2003
* Last Modified Date:
*/
using System;
namespace Client.Chapter_5___Building_Your_Own_Classes
{
public class OverloadingClasses
{
static void Main(string[] args)
{
A MyA = new A();
MyA.Display();
MyA.Display(10);
}
}
class A
{
public void Display()
{
Console.WriteLine("No Params Display Method");
}
public void Display(int A)
{
Console.WriteLine("Overloaded Display {0}", A);
}
}
}
Return an array
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Return an array.
using System;
class Factor {
/* Return an array containing the factors of num.
On return, numfactors will contain the number of
factors found. */
public int[] findfactors(int num, out int numfactors) {
int[] facts = new int[80]; // size of 80 is arbitrary
int i, j;
// find factors and put them in the facts array
for(i=2, j=0; i < num/2 + 1; i++)
if( (num%i)==0 ) {
facts[j] = i;
j++;
}
numfactors = j;
return facts;
}
}
public class FindFactors {
public static void Main() {
Factor f = new Factor();
int numfactors;
int[] factors;
factors = f.findfactors(1000, out numfactors);
Console.WriteLine("Factors for 1000 are: ");
for(int i=0; i < numfactors; i++)
Console.Write(factors[i] + " ");
Console.WriteLine();
}
}
Use a class factory
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Use a class factory.
using System;
class MyClass {
int a, b; // private
// Create a class factory for MyClass.
public MyClass factory(int i, int j) {
MyClass t = new MyClass();
t.a = i;
t.b = j;
return t; // return an object
}
public void show() {
Console.WriteLine("a and b: " + a + " " + b);
}
}
public class MakeObjects {
public static void Main() {
MyClass ob = new MyClass();
int i, j;
// generate objects using the factory
for(i=0, j=10; i < 10; i++, j--) {
MyClass anotherOb = ob.factory(i, j); // make an object
anotherOb.show();
}
Console.WriteLine();
}
}