Hi there!
I have something like this: -
abstract class BaseClass<T>
-
{
-
protected BaseClass(){}
-
}
-
-
class Class1 : BaseClass<Class1>
-
{
-
public static Class1 Instance = new Class1();
-
private Class1(){}
-
}
-
-
class Class2 : BaseClass<Class2>
-
{
-
public static Class2 Instance = new Class2();
-
private Class2(){}
-
}
-
-
...
-
public BaseClass<T> Method<T>(int z) where T: BaseClass<T>
-
{
-
switch(z)
-
{
-
case 1:
-
return Class1.Instance;
-
case 2:
-
return Class2.Instance;
-
}
-
}
-
That is very important that those classes cannot be instantiated since their construstors are private so we cannot do like
`public BaseClass<T> Method<T>(int z) where T: BaseClass<T>,` **new()**
How can I use abstract class as return type ?? I just can not work this out. Would appreciate for any assisstance here.
12 5230 vekipeki 229
Recognized Expert New Member
Please use CODE tags when posting, it makes your code much easier to read.
How about something like this: - abstract class BaseClass<T>
-
{
-
public abstract T Instance { get; }
-
}
-
-
class Class1 : BaseClass<Class1>
-
{
-
private Class1() { }
-
-
readonly Class1 _instance = new Class1();
-
public override Class1 Instance
-
{
-
get { return _instance; }
-
}
-
}
-
-
class Class2 : BaseClass<Class2>
-
{
-
private Class2() { }
-
-
readonly Class2 _instance = new Class2();
-
public override Class2 Instance
-
{
-
get { return _instance; }
-
}
-
}
Compiler cannot know know that Instance is of type T (or BaseClass<T>), if it is static, so you have to do it like this.
@vekipeki
Thank You for response,
Sorry I am newbie here, next time I will use CODE tags. My question concerns - BaseClass<T> Method<T>(int z) where T: BaseClass<T>
method how to make it work... Properties cannot be inherited in my solution it is a bit complicated. Is there a way to make that Method<T> work like I wrote it ?
vekipeki 229
Recognized Expert New Member
The important thing to notice here is that Class1.Instance is of type Class1, while Class2.Instance is of type Class2. Since they are both static and are not defined in any interface or parent abstract class, for C# compiler they are completely different.
You are telling compiler that T should be derived from BaseClass<T>, but you are not telling him that T is Class1 or Class2, so it doesn't want to allow that.
What would happen if your code would compile without errors, and somebody wrote this: - BaseClass<Class1> obj = Method<Class1>(2);
Your Method<T> would then return BaseClass<Class2>, which is not BaseClass<Class1>.
Properties cannot be inherited in my solution it is a bit complicated.
Why not?
I think the way you're trying to code it right now is a bit complicated, so try to explain what you are trying to do and then maybe it would be easier to point you in the right direction.
From your code, it looks like Method<T> should belong to the abstract class, in which case you need to be able to get an instance of T somehow (either by having a public constructor, or by using an abstract property).
By the way... the thing You wrote about
"Method<T> should belong to the abstract class, in which case you need to be able to get an instance of T"
that code: -
public BaseClass<T> Method<T>(int z) where T: BaseClass<T>
-
says itself ( " where T: BaseClass<T>" ) that T must be BaseClass or class that inherits it... so in switch statement we return Class1 or Class2 that are descendants so it should work, or I am wrong ?
vekipeki 229
Recognized Expert New Member
To call the GetStorage<T> method, you already need to know the type of T, so it isn't actually a factory.
I still don't understand why Instance needs to be static. If it was public and abstract in your base class (StorageBaseAbstract<T>), then you could simply get the singleton using: - StorageDataBase db = StorageDataBase.Instance;
or - StorageDataBase db = StorageBaseAbstract<StorageDataBase>.Instance;
But the first thing that bothers me is that it is not very obvious what the StorageBaseAbstract class does. It looks like you are only using it to save a static singleton instance of your derived classes. Furthermore, none of its methods is public, so it really doesn't do anything.
Why don't you just write: - public class StorageMemory
-
{
-
private static readonly StorageMemory _singleton
-
= new StorageMemory();
-
public static StorageMemory Instance
-
{
-
get
-
{
-
return _singleton;
-
}
-
}
-
-
private StorageMemory() { }
-
}
vekipeki 229
Recognized Expert New Member
But the example in the first article looks like this: - public class Singleton<T> where T : class
-
{
-
Singleton() { }
-
-
class SingletonCreator
-
{
-
static SingletonCreator() { }
-
-
private static T CreateInstance()
-
{
-
ConstructorInfo constructorInfo = typeof(T).GetConstructor(BindingFlags.Instance |
-
BindingFlags.NonPublic, Type.DefaultBinder, Type.EmptyTypes, null);
-
-
if (constructorInfo != null)
-
{
-
return constructorInfo.Invoke(null) as T;
-
}
-
else
-
{
-
// alternatively, throw an exception indicating the type parameter
-
// should have a private parameterless constructor
-
return null;
-
}
-
}
-
-
internal static readonly T instance = CreateInstance();
-
}
-
-
-
public static T UniqueInstance
-
{
-
get { return SingletonCreator.instance; }
-
}
-
}
Then if you add a parameterless ctor to your class - public class DatabaseStorage
-
{
-
private DatabaseStorage() {}
-
}
You can simply access (or create) the singleton using: - DatabaseStorage dbStorage = Singleton<DatabaseStorage>.UniqueInstance;
But note that UniqueInstance is public and created in abstract class.
Writing code to create an instance each time (in each derived class) doesn't make any sense (StorageMemory.Instance, for example) - what's the point in having an abstract class then?
Note that you also don't need to inherit from Singleton<T>, it is only a helper class to avoid writing singleton code multiple times.
"it is only a helper class to avoid writing singleton code multiple times" that is what i wanted to achieve there... yeah now I get Your point with that public property in abstract class, that is correct, thank You for advice
vekipeki 229
Recognized Expert New Member
As I said, that example doesn't help you a lot.
Because this code: - public sealed class ReadyForGenericSingleton : AbstractGenericSingleton<ReadyForGenericSingleton>
-
{
-
public static ReadyForGenericSingleton Instance
-
{
-
get
-
{
-
if (!Initialised)
-
{
-
Init(new ReadyForGenericSingleton());
-
}
-
return UniqueInstance;
-
}
-
}
-
-
private ReadyForGenericSingleton() { }
-
}
...is not much smaller than this code: - public sealed class ReadyForGenericSingleton
-
{
-
private static ReadyForGenericSingleton _instance
-
= new ReadyForGenericSingleton();
-
public static ReadyForGenericSingleton Instance
-
{
-
get
-
{
-
return _instance;
-
}
-
}
-
-
private ReadyForGenericSingleton() { }
-
}
If you use the last example (reflection), you don't need to write anything in your actual class.
I did use reflection code :) Thanks
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: SimonH |
last post by:
Hi all,
I would like to make a generic set of methods that could be called regardless
of the database behind the scenes.
One of the methods I would like would take a string sql statement and an
array of DataParameter objects.
The problem i have is there doesnt seem to be a generic DataParameter class
that I can instantiate. There only...
|
by: Stephen Walch |
last post by:
Error C2392 is hitting me hard!
I have a managed C++ library that implements a bunch of fixed interfaces.
For example, one interface is:
public abstract interface IDbCommand
{
public abstract new System.Data.IDbConnection Connection
}
|
by: Dave Booker |
last post by:
Is there any way to change the return types on a member function in derived
classes? E.g., something like:
public abstract class A
{
protected abstract Object f();
}
public abstract class B<T> : A
{
|
by: JAL |
last post by:
Here is my first attempt at a deterministic collection using Generics,
apologies for C#. I will try to convert to C++/cli.
using System;
using System.Collections.Generic;
using System.Text;
namespace DeterminedGenericCollection
{
// I got tired of copy and pasting IDisposable
|
by: dcew |
last post by:
Here's what I'm trying to understand; how can you store a generic collection
in a variable/field?
If I have an abstract generic collection class as follows...
public abstract class BizCollection<T> : Collection<T> where T : BizBase
{
// Collection Implementation
override void InsertItem(int index, T item)
| |
by: Lars |
last post by:
Hi,
I have a base class holding a generic list that needs
to be accessed by both the base class and its subclasses.
What is the best solution to this?
I am fairly new to generics, but I am aware of that fact
that if you have a class B, that inherits from A, then
List<Bdoes NOT inherit from List<A>. So I understand
why the example below...
|
by: Otis Mukinfus |
last post by:
I've been wrestling with this for a while and can't figure it out.
I have a generic method with the following signature:
//this compiles OK
public abstract class DataMethod
{
public abstract T Select<T>();
}
|
by: =?Utf-8?B?V2hpdG5leSBLZXc=?= |
last post by:
Hi there,
I have the following class hierarchy that isn't compiling correctly, and I
don't understand why:
public abstract class A<Twhere T : System.IComparable<T{ }
public abstract class B : System.IComparable<B>
{
public abstract int CompareTo(B other);
}
|
by: Tony |
last post by:
Hello!
I have some classes below.
I have also a generic collection class with this class header definition.
public class Farm<T: IEnumerable<Twhere T : Animal {...}
Now to my question according to a book that I read it says:
"The type of this list is determined by the type parameter T that is passed
to Farm<Tand
is constraned to be or...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language...
| |
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |