How to override a static method from a DLL Export - c#

I want to override a static method from a DLL Export
public class Export {
[DllExport] public static string plugin_name() { return Plugin.Instance.plugin_name(); }
}
public class Plugin<T> where T: Plugin<T>, new()
{
private static readonly Lazy<T> val = new Lazy<T>(() => new T());
public static T Instance { get { return val.Value; } }
protected Plugin() { }
public new static string plugin_name() { }
}
}
so these classes are in a dll file now I want that people who use the dll only do that in the main class.
public class Main : Plugin<Main> {
public override string plugin_name() {
return "a test plugin";
}
}
I have tested it for hours but failed.

You can not override static methods. You need to make a virtual or abstract instance method.
public abstract class Plugin<T> where T : new()
{
private static readonly Lazy<T> val = new Lazy<T>(() => new T());
public static T Instance { get { return val.Value; } }
protected Plugin() { }
public abstract string plugin_name();
}
public class Main : Plugin<Main> {
public override string plugin_name() => "a test plugin";
}
To make the method plugin_name static also does not make much sense, since you anyway create a singleton instance.
You can check out the code here.

Related

Using raw types in C#?

Can I use raw type in C# like Java or is there a workaround for this? I know using Raw Type in Java is bad practice but that can solve my current problem.
I have an object that has a field holding a Pool, so that it can return to that Pool whenever it's done with its job.
//C#
public class MyObject : IPoolable
{
public Pool<MyObject> pool;
}
But if there is a new kind of object (ex: MovableObject), I want my pool field has Pool<MovableObject> not Pool<MyObject>. (There are also many kinds of objects derived from MovableObject or MyObject).
In Java, I could define pool field a raw type of Pool so that there is no compiling error.
//Java
public class MyObject implements IPoolable
{
public Pool pool;
}
I'm using a method to return all kinds sof objects in both versions. In Java, it works well but in C#, it has compiling error.
//Java
static public <T extends MyObject> T createObject(Class<T> type) {
Pool<T> pool = Pools.get(type);
T obj= pool.obtain();
obj.setPool(pool); //This won't have any problem since it is raw type
return obj;
}
//C#
public static T CreateObject<T>() where T : MyObject
{
Pool<T> pool = Pools.GetPool<T>();
T obj= pool.Obtain();
obj.Pool = pool; //Error: cannot convert Pool<T> to Pool<MyAction>
return obj;
}
Edit 1: Providing other classes and Minimal, Reproducible Example
public interface IPoolable
{
void Reset();
}
public abstract class Pool<T> where T : IPoolable
{
private readonly Stack<T> freeObjects = new Stack<T>();
public Pool() { }
protected abstract T InstantiateObject(object[] args);
public T Obtain(object[] args = null)
{
return freeObjects.Count == 0 ? InstantiateObject(args) : freeObjects.Pop();
}
public void Free(T obj)
{
if (obj != null)
{
freeObjects.Push(obj);
Reset(obj);
}
}
protected virtual void Reset(T obj)
{
obj.Reset();
}
public void Clear()
{
freeObjects.Clear();
}
}
//ReflectionPool
public class ReflectionPool<T> : Pool<T> where T : IPoolable
{
public ReflectionPool() : base()
{
}
protected override T InstantiateObject(object[] args)
{
return (T)Activator.CreateInstance(typeof(T), args);
}
}
public class Pools
{
static private readonly Dictionary<Type, object> typePools = new Dictionary<Type, object>();
static public Pool<T> GetPool<T>(int max) where T : IPoolable
{
Type type = typeof(T);
if (!typePools.TryGetValue(type, out object pool))
{
pool = new ReflectionPool<T>();
typePools.Add(type, pool);
}
return (Pool<T>)pool;
}
static public Pool<T> GetPool<T>() where T : IPoolable
{
return GetPool<T>(100);
}
}
So in MyObject class, there is a method making my object doing something, after completing it, the current object need to be returned to Pool
//Base Object
public abstract class MyObject : IPoolable
{
public Pool<MyObject> pool; //This is still a problem
public void CallMe()
{
if (Act()) //If this object completing acting
{
ToPool();
}
}
public abstract bool Act();
public void ToPool()
{
pool.Free(this);
pool = null;
}
public abstract void Reset();
}
//Movable Object
public class MovableObject : MyObject
{
//public Pool<MyObject> pool; //Put this here as comment because I want it become Pool<MovableObject>
public override bool Act()
{
return true; //Return false if not reach destination
}
public override void Reset() { }
public override string ToString()
{
return "Movable";
}
}
//I'm using this class for create object I want
public class ObjectFactory
{
public static T CreateObject<T>() where T : MyObject
{
Pool<T> pool = Pools.GetPool<T>();
if(pool != null)
{
T obj = pool.Obtain();
obj.pool = pool; //Error here: Cannot implicitly convert type 'Pool<T>' to 'Pool<MyObject>'
return obj;
}
return null;
}
public static MovableObject MovableObject()
{
return CreateObject<MovableObject>();
}
}
Edit 2: Re-Updated code in edit 1

Static class derive from base change member

In C# a static class can not derive from any other class besides object.
Currently I have this base class:
public static class BaseModule
{
public static string UsedSource {get; set;}
public static Write(string text)
{
OtherStaticClass.Log(UsedSource, text);
}
}
Now, depending on which class I'm using, I want to change UsedSource.
// this does not work
internal static class ModuleA : BaseModule
{
static ModuleA(){
UsedSource = "A" // just an example
}
}
// this does not work
internal static class ModuleB : BaseModule
{
static ModuleB(){
UsedSource = "B" // just an example
}
}
Supposed to be called like this
ModuleA.Write("Hi");
ModuleB.Write("Hi");
This approach does not work because a static class cannot derive from anything else than object.
Is there any other way to change the property?
You have a lot of static classes going on here and I'm not entirely sure they're necessary. My example does not use static classes other than for the OtherStaticClass reference you have. I understand this may not be quite what you're looking for; many ways to skin this cat.
public abstract class BaseModule
{
public string UsedSource { get; set; }
public void Write(string text)
{
OtherStaticClass.Log(UsedSource, text);
}
}
public class ModuleA : BaseModule
{
public ModuleA()
{
UsedSource = "A";
}
}
public class ModuleB : BaseModule
{
public ModuleB()
{
UsedSource = "B";
}
}
To get your output then, you just need to create new instances of ModuleA and ModuleB.
var moduleA = new ModuleA();
var moduleB = new ModuleB();
moduleA.Write("Hi");
moduleB.Write("Hi");
Using a static class means using a singleton. Singletons defeat the purpose of tracking the effective dependencies of your classes.
Anyway, you can approach the problem by refactoring your code and using a factory:
In this case, just drop the static keyword and let the class be inheritable (you have to add the appropriate virtual keywords to allow proper inheritance):
public class BaseModule
{
public string UsedSource {get; set;}
public Write(string text)
{
OtherStaticClass.Log(UsedSource, text);
}
}
Then, add an additional class which holds the reference (I gave useless names, focus on the purpose):
public static class MySingleton
{
public static BaseModule _Module;
public static BaseModule Module
{
get
{
return _Module;
}
}
public static void ChangeImplementation (BaseModule module)
{
// do your checks here
_Module = module;
}
}
This way wou can achieve what you ask.
As you can see, this code has several issues, among them it's important to note that this code has global side effects and is not thread safe.
A better approach is to have drop the singleton entirely, and pass the BaseModule class (that can be inherited) as an argument of methods/constructors when needed.
I don't see that you need more than one static class. Instead separate the logic into methods in one static class.
public static class Module
{
private const string SourceA = "A";
private const string SourceB = "B";
public static WriteA(string text)
{
Write(SourceA, text);
}
public static WriteB(string text)
{
Write(SourceB, text);
}
private static Write(string source, string text)
{
OtherStaticClass.Log(source, text);
}
}
Then instead of
ModuleA.Write("Hi");
ModuleB.Write("Hi");
you'd do
Module.WriteA("Hi");
Module.WriteB("Hi");
If you can't change the BaseModule class, you can use it with other state and recover state after using:
public static class BaseModule
{
public static string UsedSource {get; set;}
public static Write(string text)
{
OtherStaticClass.Log(UsedSource, text);
}
}
internal class Writer : IDisposable
{
string _lastSource;
public Writer(string source)
{
_lastSource = BaseModule.UsedSource;
BaseModule.UsedSource = source;
}
public void Dispose()
{
BaseModule.UsedSource = _lastSource;
}
}
internal abstract class Module
{
public abstract Source { get; };
public void Write(string text)
{
using (var writer = new Writer(Source))
{
BaseModule.Write(text);
}
}
}
internal class ModuleA : Module
{
public override Source => "A";
}
internal class ModuleB : Module
{
public override Source => "B";
}
But you must ensure thread safety.
If you can change the BaseModule class:
public static class BaseModule
{
public static Write(string text, string source)
{
OtherStaticClass.Log(source, text);
}
}
internal abstract class Module
{
public abstract Source { get; };
public void Write(string text)
{
BaseModule.Write(text, Source);
}
}
internal class ModuleA : Module
{
public override Source => "A";
}
internal class ModuleB : Module
{
public override Source => "B";
}

How to call a class method from another class instance

I'm new to C#, I'm in doubt about how to make this work:
namespace Core {
public class A{
private reandonly string _var;
public A(string var){
_var=var
}
public GetValue() => return _var;
}
}
using System;
namespace Core.Resources {
public static class B{
public static void DoSomething(){
Console.Writeline($"{A.GetValue()}");
}
}
}
public class C{
static void Main(string args[]){
A a = new A("name");
a.Resources.B.DoSomething();
}
}
A is in main folder, B is in Main/Resources folder, together they make a classlib, Program.cs is using this lib. Is there a way to make this work?
If you write a.Resources you are basically trying to retrieve the member Resources of the class A, which is obviously not defined. Since B is a static class defined in the Core.Resources namespace, all you have to do is to change your code as follows:
public class C
{
public static void Main(string args[])
{
A a = new A("A");
Core.Resources.B.DoSomething();
}
}
or, alternatively, if you don't want to reference the namespace every time:
using Core.Resources;
public class C
{
public static void Main(string args[])
{
A a = new A("A");
B.DoSomething();
}
}
Note that if yuu explicitly define a public constructor for A that accepts one or more arguments, the default parameterless constructor is no more available... hence you have to pass a string to the A constructor if you don't want to see an error in your console. Alternatively, you have to rewrite your A class so that it implements a default parameterless compiler, for example:
public class A
{
private reandonly String _var;
public A() : this(String.Empty) { }
public A(String var)
{
_var = var;
}
}
EDIT AS PER OP COMMENTS AND QUESTION CHANGES
public class A
{
private reandonly String _var;
public String Var
{
get { return _var; }
}
public A(String var)
{
_var = var;
}
}
public static class B
{
public static void DoSomething(String text)
{
Console.Writeline(text);
}
}
public class C
{
public static void Main(string args[])
{
A a = new A("name");
B.DoSomething(a.Var);
}
}

C# How to treat static class as a variable

I have a static Class and within it I have multiple public static attributes. I treat this class as my global class.
However now I need to treat this class as a variable so that I can pass it to a method of another class for processing..
I can't instantiate this class.. So in effect I can only assign the variables inside this class.
Is my understanding correct or am I missing something?
public static class Global
{
public const int RobotMax = 2;
// GUI sync context
public static MainForm mainForm;
public static SynchronizationContext UIContext;
// Database
public static Database DB = null;
public static string localDBName = "local.db";
public static Database localDB = null;
public static Database ChangeLogDB = null;
public static string changeLogDBName = "ChangeLog.db";
}
Let say I have a class like this, and I need to somehow keep a copy of this in another class maybe
public static class Global_bk
{
public const int RobotMax = 2;
// GUI sync context
public static MainForm mainForm;
public static SynchronizationContext UIContext;
// Database
public static Database DB = null;
public static string localDBName = "local.db";
public static Database localDB = null;
public static Database ChangeLogDB = null;
public static string changeLogDBName = "ChangeLog.db";
}
I need to copy the contents from Global to Global_bk.
And after that I need to compare the contents of the two classes in a method like
static class extentions
{
public static List<Variance> DetailedCompare<T>(T val1, T val2)
{
List<Variance> variances = new List<Variance>();
FieldInfo[] fi = val1.GetType().GetFields();
foreach (FieldInfo f in fi)
{
Variance v = new Variance();
v.Prop = f.Name;
v.valA = f.GetValue(val1);
v.valB = f.GetValue(val2);
if (!v.valA.Equals(v.valB))
variances.Add(v);
}
return variances;
}
}
class Variance
{
string _prop;
public string Prop
{
get { return _prop; }
set { _prop = value; }
}
object _valA;
public object valA
{
get { return _valA; }
set { _valA = value; }
}
object _valB;
public object valB
{
get { return _valB; }
set { _valB = value; }
}
}
So on my main form, how do I go about calling the compare method and passing the static Global class inside?
example: extentions.DetailedCompare(Global, Global_bk) ? Of course this would give me an error because I cant pass a type as a variable.
Please help me, this is driving me nuts...
How about the singleton pattern ? You can pass reference to shared interface (IDoable in exable below) and still have just one instance.
I.E.:
public interface IDoable {
int Value { get; set; }
void Foo();
}
public static class DoableWrapper {
private MyDoable : IDoable {
public int Value { get;set; }
public void Foo() {
}
}
private static IDoable s_Doable = new MyDoable();
public static IDoable Instance {
get { return s_Doable; }
}
}
Singleton is the way to go here. You can do it like this:
internal class SomeClass
{
private static SomeClass singleton;
private SomeClass(){} //yes: private constructor
public static SomeClass GetInstance()
{
return singleton ?? new SomeClass();
}
public int SomeProperty {get;set;}
public void SomeMethod()
{
//do something
}
}
The GetInstance Method will return you a SomeClass object that you can edit and pass into whatever you need.
You can access the members with classname.membername.
internal static class SomeClass
{
public static int SomeProperty {get;set;}
public static void SomeMethod()
{
//do something
}
}
static void main()
{
SomeClass.SomeProperty = 15;
SomeClass.SomeMethod();
}
The only way you are going to obtain a variable with the "class" information is using reflection. You can get a Type object for the class.
namespace Foo {
public class Bar
{
}
}
Type type = Type.GetType("Foo.Bar");
Otherwise, if you are really describing a class "instance" then use an object and simply instantiate one.
C# offers no other notation for class variables.

How do you implement constructor injection in a factory?

When you're using a factory pattern, how do you inject dependencies into constructors at runtime?
I'm building Foos with different formats - boolean, array, freetext, matrix, etc. That format list will grow as we find different uses for Foo. Here's my basic core domain:
public interface IFoo
{
FooFormat Format { get; }
}
public class Foo : IFoo
{
private FooFormat _format;
internal Foo(FooFormat format)
{
_format = format;
}
public FooFormat Format { get { return _format; } }
}
public abstract class FooFormat
{
}
public class DefaultFooFormat : FooFormat
{
}
public class BooleanFooFormat : FooFormat
{
public IList<bool> Values { get; set; }
}
public class ArrayFooFormat : FooFormat
{
private IList<string> _values;
public ArrayFooFormat(IList<string> values)
{
_values = values;
}
public IList<string> Values { get { return _values; } }
}
IFoo is decorated for the consumer context:
public abstract class FooDecorator : IFoo
{
private IFoo _foo;
protected FooDecorator(IFoo foo)
{
_foo = foo;
}
public FooFormat Format
{
get { return _foo.Format; }
}
protected IFoo foo
{
get { return _foo; }
}
}
I don't want my consumer to instantiate a Foo directly, so I force them to use a factory:
public abstract class FooFactory
{
protected IFoo Build<T>()
{
FooFormat format = GetFormat<T>();
return new Foo(format);
}
private FooFormat GetFormat<T>()
{
if (typeof(T) == typeof(ArrayFooFormat)) return new ArrayFooFormat(new List<string>());
if (typeof(T) == typeof(BooleanFooFormat)) return new BooleanFooFormat();
return new DefaultFooFormat();
}
}
And even then, they need to derive a factory from my abstract factory for their particular context.
I'm specifically building foos in an html context, like so:
public class HtmlFoo : FooDecorator
{
public HtmlFoo(IFoo foo) : base(foo) { }
public string ToHtml()
{
return "<div>" + this.Format.ToString() + "</div>";
}
}
public class HtmlFooFactory : FooFactory
{
public IFoo BuildFoo<T>()
{
IFoo foo = Build<T>();
return new HtmlFoo(foo);
}
}
public class HtmlFooConsumer
{
public void DoSomeFoo()
{
var factory = new HtmlFooFactory();
var htmlBooleanFoo = factory.BuildFoo<BooleanFooFormat>();
var htmlArrayFoo = factory.BuildFoo<ArrayFooFormat>();
}
}
My problem is in my abstract FooFactory: I'm always injecting an empty value list into my ArrayFooFormat. I want to be able to pass in a value list from the consumer. For other FooFormats, I want to pass in the right constructor arguments from the consumer. But I want to keep the public API dead simple - I don't want a bunch of overloads on BuildFoo().
So how do I pass a custom value list into the factory.BuildFoo<T>() call from inside HtmlFooConsumer.DoSomeFoo()? Any ideas, stackoverflow gurus?
Maybe you can do something along these lines where your abstract FooFormat becomes IFooFormat and a generic FooFormat provides an Init method that gets passed the parameter.
Then a single overload of Build lets you pass in the parameter.
public interface IFooFormat
{
}
public class FooFormat<TValue> : IFooFormat
{
private TValue _value;
public void Init(TValue value)
{
_value = value;
}
public TValue Value
{
get { return _value; }
}
}
public class ArrayFooFormat : FooFormat<IList<string>> { }
public class BooleanFooFormat : FooFormat<bool> { }
public class DefaultFooFormat : IFooFormat { }
public interface IFoo { }
public class Foo : IFoo
{
private IFooFormat _format;
internal Foo(IFooFormat format)
{
_format = format;
}
public IFooFormat Format { get { return _format; } }
}
public class FooFactory
{
protected IFoo Build<TFormat, TArg>(TArg arg) where TFormat : FooFormat<TArg>, new()
{
TFormat format = new TFormat();
format.Init(arg);
return new Foo(format);
}
protected IFoo Build<TFormat>() where TFormat : IFooFormat, new()
{
return new Foo(new TFormat());
}
}
A factory is basically the object oriented version of a static variable. I'd avoid using one alltogether. Instead of forcing clients to use a factory, perhaps you can simply inject objects into their constructors, sidestepping the need for a factory.

Categories