Create a class in C# such that it can't be instantiated and satisfy following conditions :
Create public class in C# such that following conditions are satisfied :
- The class cannot be instantiated.
- A function from that class can be called by other class.
I tried this way :
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();
}
But my answer was wrong.So, please help me out.
You can create a class like as follows to meet your goal
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();
}
}
Making the constructor of A private would bar it from instantiating from another class. And the static method GetA will return an object of A instatiating it privately which you can use from any class.
you can use static class if you don't like allow to instantiate it use static class, The best sample for it is Math
class, Also if you want to have a single instance you can use singleton.
MSDN sample:
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;
}
}
}
And for creating class singleton do this:
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();
}
}
精彩评论