在C#中创建公共类,以满足以下条件:
我试过这种方式:
public abstract class A {
public static void fun()
{
// do process.
}
}
public class B : A
{
// Now A can't be instantiated being abstract.
// And you can call its function like this :
A.fun();
}
但我的回答是错的。所以,请帮助我。
答案 0 :(得分:1)
您可以按照以下方式创建一个类来实现目标
public class A
{
private A()
{
}
public static A GetA()
{
return new A();
}
public void Foo()
{}
}
public class B
{
public void Foo2()
{
A a = A.GetA();
a.Foo();
}
}
使A的构造函数禁止它从另一个类实例化。静态方法GetA将返回一个私有实例化的对象,你可以在任何类中使用它。
答案 1 :(得分:1)
你可以使用静态类,如果你不喜欢允许实例化它使用静态类,最好的样本是Math
类,如果你想拥有一个实例,你可以使用单例。
MSDN样本:
public static class TemperatureConverter
{
public static double CelsiusToFahrenheit(string temperatureCelsius)
{
// Convert argument to double for calculations.
double celsius = System.Double.Parse(temperatureCelsius);
// Convert Celsius to Fahrenheit.
double fahrenheit = (celsius * 9 / 5) + 32;
return fahrenheit;
}
public static double FahrenheitToCelsius(string temperatureFahrenheit)
{
// Convert argument to double for calculations.
double fahrenheit = System.Double.Parse(temperatureFahrenheit);
// Convert Fahrenheit to Celsius.
double celsius = (fahrenheit - 32) * 5 / 9;
return celsius;
}
}
class TestTemperatureConverter
{
static void Main()
{
System.Console.WriteLine("Please select the convertor direction");
System.Console.WriteLine("1. From Celsius to Fahrenheit.");
System.Console.WriteLine("2. From Fahrenheit to Celsius.");
System.Console.Write(":");
string selection = System.Console.ReadLine();
double F, C = 0;
switch (selection)
{
case "1":
System.Console.Write("Please enter the Celsius temperature: ");
F = TemperatureConverter.CelsiusToFahrenheit(System.Console.ReadLine());
System.Console.WriteLine("Temperature in Fahrenheit: {0:F2}", F);
break;
case "2":
System.Console.Write("Please enter the Fahrenheit temperature: ");
C = TemperatureConverter.FahrenheitToCelsius(System.Console.ReadLine());
System.Console.WriteLine("Temperature in Celsius: {0:F2}", C);
break;
default:
System.Console.WriteLine("Please select a convertor.");
break;
}
}
}
为了创建类单例,请执行以下操作:
public sealed class MyClass
{
MyClass()
{
}
public static MyClass Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly MyClass instance = new MyClass();
}
}