I need to share some common functionality between two static classes:
public static class Class
{
public static void ClassMethod()
{
SharedMethod<object>();
}
//ideally a private method
internal static void SharedMethod<T>()
{
}
}
public static class GenericClass<T>
{
public static void GenericClassMethod()
{
SharedMethod<T>();
}
}
Is there a better design here? internal is my last choice, but really the method SharedMethod has no significance outside those two classes.
Requirements:
I can't combine them to a single class, I need them separately, one generic and other not.
The classes need not be strictly static, but they shouldn't be instantiable or inheritable.
SharedMethod can fall in either class, it doesn't matter.
This workaround doesn't meet all 3 requirements (which is impossible imo) but it made up for the same functionality I wanted.
I ended up using a single class as Marc suggested in comments. But then I had the generic class nested inside the non generic class to act for the generic functionality.
public static class Class
{
public static void ClassMethod()
{
SharedMethod<object>();
}
static void SharedMethod<T>()
{
//----
}
public static void GenericClassMethod<T>()
{
return GenericClass<T>.SharedMethod();
}
static class GenericClass<T>
{
static void SharedMethod()
{
//available here since private members of outer class is visible to nested class
SharedMethod<T>();
}
}
}
So now, even though the calling has to be done little differently from how I wanted it originally in the question, functionally both are equal.
First I thought you can't meet the 3 rules, but then I thought about reflection, and I came up with something that works, but that shouldn't be used unless you really don't have any other way of accomplishing what you need
I don't recommend using it but just for fun I'll post the code:
public static class ClassA
{
private static void sharedMethod<T>() { }
public static void ClassMethod()
{
sharedMethod<object>();
}
}
public static class GenericClass<T>
{
static MethodInfo sharedMethodInfo;
static GenericClass()
{
MethodInfo mi = typeof(ClassA).GetMethod("sharedMethod", BindingFlags.NonPublic | BindingFlags.Static);
sharedMethodInfo = mi.MakeGenericMethod(new Type[] { typeof(T) });
}
public static void GenericClassMethod()
{
sharedMethodInfo.Invoke(null, null);
}
}
Declare the classes as sealed - that way they won't be inheritable.
If you change the permission from private to protected that way anything in your application can see the method but will be invisible to another application trying to use your methods.
Hope this helps !
If you can use the singleton pattern, you can have 2 classes, with the generic class inheriting from the standard one. Also you can keep your static methods, here is what it can look like:
internal class ClassA
{
private static ClassA _instance;
private static ClassA Instance
{
get
{
if (_instance == null) _instance = new ClassA();
return _instance;
}
}
protected void sharedMethod<T>() { }
public static void ClassMethod()
{
Instance.sharedMethod<object>();
}
}
public sealed class GenericClass<T> : ClassA
{
private static GenericClass<T> _instance;
private static GenericClass<T> Instance
{
get
{
if (_instance == null) _instance = new GenericClass<T>();
return _instance;
}
}
public static void GenericClassMethod()
{
Instance.sharedMethod<T>();
}
}
Related
Say I have a generic class Foo, that has a variable that is protected
public class Foo<T>
{
protected bool knowsFu;
}
I also have 2 sub-classes: Bar and Pipe
public class Bar : Foo<Bar> {}
public class Pipe : Foo<Pipe> {}
It is actually possible for me to access the knowsFu in Pipe FROM Bar, e.g.:
public class Bar : Foo<Bar>
{
void UpdateFuInOtherClass(Pipe p)
{
p.knowsFu = false;
}
}
Is this intended behaviour? (If so, what would be the usecase?)
Is there a way for me to prevent other Foo-Subclasses from modifying/reaching the protected variable inside of my current subclass?
More specifically: I'm using a generic class to implement the Singleton-Pattern:
https://en.wikipedia.org/wiki/Singleton_pattern
However, I'm currently able to access any singleton's protected instance-variable, as long as I am inside of another Singleton. Is there a way to prevent this?
EDIT: It might be relevant to note that the protected variable (knowsFu) is actually STATIC as well.
EDIT2: Ok, maybe the example was abit too generic.. here's how I'm actually currently implementing it:
why use Singleton? A:The platform I'm working on is Unity3D, in which the pattern is used frequently
I have a generically typed abstract class SingletonBehaviour
public abstract class SingletonBehaviour<T> where T : MonoBehaviour
{
public static T Instance { get { return instance; } }
protected static T instance { get; private set; } }
// Loading is done through Unitys Awake-Method
}
One of the Singleton-Objects that I'm using is the APIManager
public class APIManager : SingletonBehaviour<APIManager>
{
// Methods like SendHTTPPost(), HTTPGet(), etc.
}
However, since most of my projects need some better API-implementation than that, what I'm currently doing is:
public class ProjectAAPIManager : APIManager
{
// Overriding Instance so my return value is not APIManager but instead ProjectAAPIManager
public static new ProjectAAPIMamager Instance { get { return (ProjectAAPIManager)instance; } }
}
This ^ is the reason my (inner) instance-variable is protected, and not private.
However, because of this, any other SingletonBehaviour in my project can now access the (inner) instance-variable on my ProjectAAPIManager
public class GameController : SingletonBehaviour<GameController>
{
private void AMethod()
{
// Accessing inner variable instead of public one
ProjectAAPIManager.instance.DoSomething();
}
}
As it's only the getter, this currently does not really matter. But what if I'd need access to the setter in my subclass as well?
Also: would it be worth it to generically type my APIManager as well?
Your question is nothing short of bewildering. How can you make a protected member not be accesible from a derived class? Well, a good start is not making it protected.
protected is by definition exactly what you don't want, so don't use it! Use private instead.
If what you are asking is how to make it a readonly member when accessed from derived types, you have two options:
Declare it as readonly in the base class if possible.
Use a protected property instead with a private setter.
Many novice coders seems to think protected members aren't part of the public surface of the type but they really are, as long as the class can be extended. As such, the rules of public members apply: never expose public fields unless they are readonly or constants, use properties instead.
You should not have classes that implement your generic singleton class.
Otherwise, by default, your protected fields will be accessible by the subclasses (it's what "protected" keyword does)
Instead, you should do something like this:
class Program
{
static void Main(string[] args)
{
var barInstance = Foo<Bar>.GetInstance();
}
}
public class Foo<T> where T : new()
{
protected bool knowsFu;
private static T _instance;
public static T GetInstance()
{
if (_instance == null)
_instance = new T();
return _instance;
}
}
public class Bar
{
public Bar()
{
}
}
Edit 1:
To use a singleton, you should not make another class implement the singleton behavior (This is not how the singleton pattern works).
To use the same classes as your second example, you should do something like this.
public class SingletonBehaviour<T> where T : new()
{
public static T Instance
{
get
{
if(instance == null)
instance = new T()
return instance;
}
}
private static T instance { get; set; }
}
public class APIManager // This class should not inherit from the SingletonBehavior class
{
// Methods like SendHTTPPost(), HTTPGet(), etc.
}
public class ProjectAAPIManager : APIManager
{
public ProjectAAPIManager GetInstance() => SingletonBehavior<ProjectAAPIManager>.Instance();
}
Hi i want to have a class that cannot be instantiated but can be added as a static field to another class but i could not achieve it;
Here is what i've done;
public class ValueListManager
{
public static Operations myOps { get { return new Ops(); } }
}
public interface Operations
{
void Call();
}
public class Ops : Operations
{
public void Call()
{
}
}
I dont' want the Ops class to be instantiated anywhere else. Basically I want to be able to;
ValueListManager.Operations.Call();
But i dont want to be able to use the ops class like;
var ops = new Ops();
Is there a way to achieve this?
You can achieve that by declaring the Ops class as a private class within the ValueListManager class where you want to use it:
public class ValueListManager
{
private class Ops : Operations
{
public Ops()
{
}
public void Call()
{
}
}
public static Operations myOps { get { return new Ops(); } }
}
Note, that in this example based on your code, a new instance of the Ops class is created every time you access the myOps property. If you don't want that, you need to store the Ops instance in a static field once it is created and use that in the Getter of the property.
As I understand you want to instantiate this class only once and later use it.
You can use Singletone pattern, you can also use inheritance with this pattern.
public class Ops: Operations
{
private static Ops instance;
private Ops() {}
public static Ops Instance
{
get
{
if (instance == null)
{
instance = new Ops();
}
return instance;
}
}
public void Call()
{
// do something
}
}
and where you want to use it you can call its method:
Ops.Instance.Call()
If you don't want to nest your classes for some reason, and don't want to basically change anything except the Ops class itself, you could put your code into a different assembly (add a class library to your solution), and make the constructor internal:
public class ValueListManager
{
public static Operations myOps { get { return new Ops(); } }
}
public class Ops : Operations
{
internal Ops() {}
public void Call()
{
}
}
Then you'd only need to add a reference to that assembly from the one you want to use that, you'd not need to change any other code.
The constructor (thus new Ops()) can only be accessed from that assembly, code in other assemblies won't be able to new.
This is very similar to the design pattern singleton, but it is unclear from your code if you want only one instance or if you don't want to instantiate it from elsewhere?
If it is a single instance you're after the most recommended way to implement a singleton in c# is using the static constructor:
public class Single
{
private static Single instance;
private Single() { }
static Single()
{
instance = new Single();
}
public static Single Instance
{
get { return instance; }
}
}
Most other ways have (at least a theoretical) risk of threading issues.
However it should be noted that the singleton pattern (and typically extensive use of static methods) is in some contexts an indication of a bad design.
Some time ago I learned of the Singleton implementation that only permits a single instance of a class object by hiding the class initializer and using a private static reference of the object within itself, and a public GETTER that references that private reference -
public class Foo : IDisposable{
private static Foo _Instance;
public static Foo Instance{ get{ return Foo._Instance ?? new Foo(); }
private Foo(){ Foo._Instance = this; }
public void Dispose(){ Foo._Instance = null; }
}
I love this quite a lot - it is especially nice for windows that I want accessible application wide.
One thing that I would really like is to be able to implement a generic sort of Singleton Window class upon which a real window could be built and then accessed like this - Is this possible? My thinking was something like -
public class SingletonWindow : Window {
private static SingletonWindow _Instance;
public static SingletonWindow Instance{ get{ return SingletonWindow._Instance ?? new SingletonWindow(); } }
private SingletonWindow(){ SingletonWindow._Instance = this; }
private sealed override void OnClosed(EventArgs E){ SingletonWindow._Instance = null; }
}
But... something inside me that I can't quite voice tells me that this will absolutely positively fail miserably. Can someone tell me why this would fail (if, indeed it will fail), if it is possible to achieve what I am attempting to achieve here, and how I might go about doing so if it is possible?
Personally, I'm not a fan of singletons.
That said, if you want a generic class, make it a generic class. You will have to have a static constructor on your derived class that will provide a route to the private constructor to your generic class, but that's about it.
public abstract class Singleton<T> where T : Window, Singleton<T>
{
protected static Func<T> create;
private static T instance;
public static T Instance { get { return instance ?? (instance = create()); } }
private sealed override void OnClosed(EventArgs e)
{
instance = null;
}
}
public class MyWindow : Singleton<MyWindow>
{
static MyWindow()
{
create = () => new MyWindow();
}
private MyWindow() { }
}
Then you can access the instance on your derived class as if it was a normal singleton.
var myWindow = MyWindow.Instance;
I have a program that needs to be able to interface with multiple platforms ie read/write files, read/write database or read/write web requests. The platform interface is selected from configuration and does not change while the application is running. I have a single read/write interface class which is inherited by the platform specific classes so that this is abstracted from the rest of the program.
My problem is that I have 10 classes in my framework that will need to use this interface. Instead of making multiple instances of this class, or passing a single reference to every class, I figured it would make sense to make the interface static. Unfortunately I have just learned that Interfaces cannot have static methods, static methods cannot call non-static methods and static methods cannot be abstract.
Can anyone show me another method of approaching this situation?
Edit:
Thanks for everyone's input, here is my solution based on the example given by Patrick Hofman (thank you!)
interface TheInterface
{
void read();
void write();
}
public class X : TheInterface
{
public void read() { //do something }
public void write() { //do something }
}
public class Y : TheInterface
{
public void read() { //do something }
public void write() { //do something }
}
public class FileAccessor
{
public static TheInterface accessor;
public static TheInterface Accessor
{
get
{
if(accessor) return accessor;
}
}
}
This can be called by any class as:
static void Main(string[] args)
{
switch (Config.interface)
{
case "X":
FileAccessor.accessor = new Lazy<X>();
case "Y":
FileAccessor.accessor = new Lazy<Y>();
default:
throw new Lazy<Exception>("Unknown interface: " + Config.interface);
}
FileAccessor.Accessor.read();
}
Indeed, interfaces, or abstract classes can't be static themselves, but the further implementation can. Also, you can use the singleton pattern to make your life easier, and allow inheritance, etc.
public class X : ISomeInterface
{
private X() { }
public static X instance;
public static X Instance
{
get
{
return instance ?? (instance = new X());
}
}
}
Or, using Lazy<T>:
public class X : ISomeInterface
{
private X() { }
public static Lazy<X> instanceLazy = new Lazy<X>(() => new X());
public static X Instance
{
get
{
return instance.Value;
}
}
}
Disclaimer: I am the author of the library described below.
I don't know if this helps you, but I have written a library (very early version yet) that allows you to define static interfaces, by defining normal interfaces and decorating their methods with an attribute named [Static], for example:
public interface IYourInterface
{
[Static]
void DoTheThing();
}
(Note that you don't explicitly add this interface to your implementations.)
Once you have defined the interface, you can instantiate it from within your code with any valid implementation you choose:
return typeof(YourImplementation).ToStaticContract<IYourInterface>();
If the methods can't be found in YourImplementation, this call fails at runtime with an exception.
If the methods are found and this call is successful, then the client code can polymorphically call your static methods like this:
IYourInterface proxy = GetAnImplementation();
proxy.DoTheThing();
You can make a Static Class which has Variable of your Interface.
public static class StaticClass
{
public static ISomeInterface Interface;
}
Now you can access the Instance from everywhere in your Framwork
static void Main(string[] args)
{
StaticClass.Interface = new SomeClass();
}
Greetings!
I have a class which is used like a cache:
public sealed class MyCache<T> : IDisposable
{
private ReaderWriterLockSlim theLock = new ReaderWriterLockSlim();
private Dictionary<int, T> theCache = new Dictionary<int, T>();
public void Add(int key, T value)
{
// ... logic/code to add to the dictionary
}
public void Clear()
{
theLock.EnterWriteLock();
try
{
theCache.Clear();
}
finally
{
theLock.ExitWriteLock();
}
}
}
This cache is used many times, so there are often multiple instances of this at any given time.
Example 1:
public static class SpecialPageCache
{
public static MyCache<string> SpecialPage = new MyCache<string>();
}
Example 2:
public static class DdListCache
{
public static MyCache<List<int, string>> DdlList = new MyCache<List<int, string>>();
}
And so on.
I have a service that can clear the caches on-demand, but unfortunately, each one has to be cleared like so:
private void ClearThemAll()
{
SpecialPageCache.SpecialPage.Clear();
DdListCache.DdlList.Clear();
// repeat for all other caches that may exist ...
}
How can I use reflection (or something else?) to call each cache's Clear() method without having to explcitly do it for each one like I do in the above ClearThemAll() method?
Ick. You'd have to go through all the types in the assembly that you're interested in, and check all the static fields. This is made even more interesting because it's a generic type. Your life will be simpler if you have a nongeneric base class:
public abstract class MyCache : IDisposable
{
public abstract void Clear();
}
public sealed class MyCache<T> : MyCache
{
// ...
}
Then at least it's relatively easy to detect whether the type of a particular field is a MyCache, fetch its value and call Clear on it without messing around with reflection over generic types.
This is generally a nasty problem though - are you sure you want to clear all the caches like this, without really "understanding" which caches you're clearing?
public interface ICache : IDisposable
{
void Clear();
}
public interface ICache<T> : ICache
{
}
public abstract class CacheBase<T> : ICache<T>
{
}
public sealed class SpecialPageCache : CacheBase<string>
{
internal SpecialPageCache()
{
}
}
public static class CacheFactory
{
private static List<ICache> cacheList = new List<ICache>();
public static TCache Create<TCache>()
where TCache : ICache, new()
{
var result = new TCache();
cacheList.Add(result);
return result;
}
public static void ClearAll()
{
cacheList.ForEach((c) => c.Clear());
}
}
You could store references to all of your instanced caches in a list. Then iterate same list, and call Clear on each MyCache. =)
Reflection sounds nasty. Without knowing more about your object lifetime, would the following work?
public abstract class MyCacheBase : IDisposable {
public static List<MyCache> caches = new List<MyCache>();
public MyCacheBase() {
caches.Add(this); // Add all constructed caches to the list
}
public static void ClearAllCaches() {
foreach (MyCache cache in cache) // clear all constructed
cache.Clear(); // caches in the list.
}
public void Finalize() {
Dispose();
}
public void Dispose() {
caches.Remove(this); // Remove disposed classes from the list
}
public abstract void Clear();
}
public sealed class MyCache<T> : MyCacheBase
{
// Rest of the implementation
}
(Thanks to Jon for noting the genericity. Almost missed it.)
If you want to have something like user specific caches you could add a user specific CacheFactory which would keep track of the caches created through it and its ClearAll() method would only clear those caches.
Why do you need to specifcally clear them are they using resources which need to be released ?
I'm wondering if you couldnt use the System.WeakReference so that the cache is garbarge collected as and when ?
http://msdn.microsoft.com/en-us/library/system.weakreference.aspx
This sound really familiar to how Inversion of Control containers work. Why not just have something like a
Dictionary<Type, Dictionary<int, object>>
All of the functions would then take a type T and then use that type to look up the appopriate dictionary. One static MyCache could handle all your type and it could be disposed with one call.
If you really want to do reflection then you'd do something like this:
List<object> caches;
foreach (object obj in caches)
{
Type t = obj.GetType();
MethodInfo m = t.GetMethod("Clear");
// Object does not have a public instance method named "Clear"
if (m == null) { continue; }
m.Invoke(obj, new object[0]);
}