I'm trying to write this more generically:
public static CormantRadDock RecreateDock(RadDockSetting settings)
{
CormantRadDock dock = new CormantRadDock();
settings.SetSettings(dock);
Logger.DebugFormat("Recreated dock {0}", dock.ID);
return dock;
}
I have this:
public static T Recreate<T>() where T : new()
{
T _control = new T();
//settings.SetSettings(dock);
Logger.DebugFormat("Recreated control {0}", (_control as Control).ID);
return _control;
}
Generic Solution:
public interface ISetting<T>
{
void SetSettings(T obj);
}
public void SetSettings(CormantRadDock dock)
{
// do stuff with dock
}
Thanks!
Is this what you're trying to do?
// move the generic type parameter up here so the interface is generic
// and not the method definition
public interface ISetting<T>
{
void SetSettings(T obj);
}
Then you can implement it successfully in a class:
public class SomeClass: ISetting<YourSettingType>
{
public void SetSettings(YourSettingType obj) { ... }
}
either
public abstract class ISetting<T>
{
public abstract void SetSettings<T>(T obj);
}
public void SetSettings<T>(T dock)
{
// do stuff with dock
}
or
public abstract class ISetting<T>
{
public abstract void SetSettings(T obj);
}
public void SetSettings(T dock)
{
// do stuff with dock
}
How about this:
public interface ICanBeRecreated<T>
{
T Recreate();
}
public class CormantDock : ICanBeRecreated<CormantDock>
{
private RadDockSetting _settings;
private void ApplySettings(RadDockSetting settings)
{
// apply settings
}
public CormantDock Recreate()
{
var dock = new CormantDock;
dock.ApplySettings(_settings);
}
}
Related
My goal is to have the Abstract class update on its own once Consume is called on one of the derived classes.
Imagine this:
public interface IConsumable
{
void Consume();
}
public abstract class AbstractConsumable : IConsumable
{
private bool _consumed = false;
public virtual void Consume()
{
_consumed = true;
}
}
public class HealthyConsumable: AbstractConsumable
{
public override void Consume()
{
// Do something healthy and ...
base.Consume(); // Would like to avoid this...
}
}
public class PoisonousConsumable: AbstractConsumable
{
public override void Consume()
{
// Do something poisonous and ...
base.Consume(); // Would like to avoid this...
}
}
What I would like to achieve here is not having to call base.Consume() on the override methods, but still have the abstract class set _consumed once the derived classes call their Consume() methods.
You could make Consume none virtual and within it you called another protected virtual (or abstract method) that can contain code that be change by sub classes. Consumers of your class can only call the public Consume method but this will intern call the sub class implementation specific code
public interface IConsumable
{
void Consume();
}
public abstract class AbstractConsumable : IConsumable
{
private bool _consumed = false;
public void Consume()
{
_consumed = true;
InternalConsumerBehaviour();
}
protected virtual void InternalConsumeBehaviour()
{
//default do nothing could potentially mark this method abstract rather than virtual its up to you
}
}
public class HealthyConsumable: AbstractConsumable
{
protected override void InternalConsumeBehaviour()
{
// Do something healthy and ...
}
}
public class PoisonousConsumable: AbstractConsumable
{
protected override void InternalConsumeBehaviour()
{
// Do something poisonous and ...
}
}
If I get what you're asking right you could do something like this:
public interface IConsumable
{
void Consume();
}
public abstract class AbstractConsumable : IConsumable
{
private bool _consumed = false;
public abstract void ConsumeEffects();
public void Consume()
{
this.ConsumeEffects();
_consumed = true;
}
}
public class HealthyConsumable: AbstractConsumable
{
public override void ConsumeEffects()
{
// Do something healthy and ...
// Consume will get called in the base
}
}
public class PoisonousConsumable: AbstractConsumable
{
public override void ConsumeEffects()
{
// Do something poisonous and ...
// Consume will get called in the base
}
}
I use the standard DataGridView from the toolbox menu.
I do validation of each of the cells in the DataGridView by event cellEditEnd. It looks like this:
private void dataGrid_CellEditEnding(object sender,DataGridCellEditEndingEventArgs e)
{
// Below I demonstrate pseudo code for brevity
if(cell.name.value is not Number){
print "Wrong cell value";
}
}
So, in another form (WinForms) I have functionality, that imports data from an Excel file and displays it in the DataGridView.
I need to validate the Excel data before insertion in each cell. For that I can use event CellValidation. But I don’t want to repeat the same code, that I used in dataGrid_CellEditEnding method.
How can I avoid this reiteration of code?
You can take a look into the chain of responsability design pattern, your code will be configurable and more object oriented, will look something like this:
public interface IHandler
{
void Handle(string value);
}
public abstract class CellRequestTemplate : IHandler
{
protected readonly IHandler _next;
protected CellRequestTemplate(IHandler next)
{
_next = next ?? throw new ArgumentNullException(nameof(next));
}
public abstract void Handle(string value);
}
public sealed class FirtsRuleForCell : CellRequestTemplate
{
public FirtsRuleForCell(IHandler next) : base(value, next) { }
public override void Handle(string value)
{
if(value is number)
{
_next.Handle(value);
}
else
{
//print "Wrong cell value";
}
}
}
public sealed class SecondRuleForCell : CellRequestTemplate
{
public SecondRuleForCell(IHandler next) : base(value, next) { }
public override void Handle(string value)
{
//if some validation
//do something
//else
//
_next.Handle(value);
}
}
public sealed class EndOfChain : IHandler
{
public void Handle(string value)
{
throw new InvalidOperationException("End of Chaing, cant handle");
}
}
public interface IHandleCellFactory
{
IHandler CreateHandler();
}
public sealed class Form1GridHandler : IHandleCellFactory
{
public IHandler CreateHandler()
{
return new FirtsRuleForCell(new SecondRuleForCell(new EndOfChain()));
}
}
public sealed class Form2GridHandler : IHandleCellFactory
{
public IHandler CreateHandler()
{
return new SecondRuleForCell(new EndOfChain());
}
}
public abstract class ClientCode
{
private void dataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
// Below I demonstrate pseudo code for brevity
var valueToHandle = string.Empty; //cell.name.value;
var handler = new Form1GridHandler().CreateHandler();
handler.Handle(valueToHandle);
//continue with Execution code
}
}
For more info about the design patter, look at this link as reference.
Hope this helps, regards!
How about creating a static ValidationHelper class, with all your validation methods in it, and then calling those when required.
public static class ValidationHelper
{
public static void ValidateIsNumeric(string value)
{
if(value is not Number){
print "Wrong cell value";
}
}
}
Which you could then call:
private void dataGrid_CellEditEnding(object sender,DataGridCellEditEndingEventArgs e)
{
ValidationHelper.ValidateIsNumeric(cell.name.value);
}
I have an interface IInterface and it looks something like below -
public interface IInterface
{
void SomeMethod1();
void SomeMethod2();
void SomeMethod3();
.
.
.
}
One of the implementations is something like -
public class Implementation : IInterface
{
private Object obj;
public Implementation(Object obj)
{
this.obj = obj;
// Do Something
}
public void SomeMethod1()
{
lock(obj)
{
// Do Something
}
}
public void SomeMethod2()
{
// Do Something
}
public void SomeMethod3()
{
lock(obj)
{
// Do Something
}
}
.
.
.
}
How to pass a static readonly instance of type Object while registering Implementation class with type IInterface via unity configuration?
My preferred approach is probably to create a factory for creating IInterfaces
public interface IInterface
{
void SomeMethod1();
}
public interface IInterfaceFactory
{
IInterface CreateInterface();
}
public class StandardInterfaceFactory : IInterfaceFactory
{
// Define your static lock object here. Other customers
// can define their own IInterfaceFactory to use a
// different lock object.
private static readonly object lockObject = new object();
public IInterface CreateInterface()
{
return new StandardInterface(lockObject);
}
}
public class StandardInterface : IInterface
{
private readonly object lockObject;
public StandardInterface(object lockObject)
{
this.lockObject = lockObject;
}
public void SomeMethod1()
{
lock (this.lockObject)
{
Console.WriteLine("I've locked on " + lockObject);
}
}
}
Your unity configuration and client code will then look like this.
void Main()
{
IUnityContainer container = new UnityContainer();
// This mapping can be done trivially in XML configuration.
// Left as an exercise for the reader :)
container.RegisterType<IInterfaceFactory, StandardInterfaceFactory>();
IInterfaceFactory factory = container.Resolve<IInterfaceFactory>();
IInterface myInterface = factory.CreateInterface();
myInterface.SomeMethod1();
}
The idea of the project is html renderer.
But i wanted to do it more dynamic by using Strategy design pattern(not sure if its strategy :D).
RenderStrategy:
public abstract class RenderStrategy
{
private Element _RenderElement;
public RenderStrategy(Element renderElement)
{
this._RenderElement = renderElement;
}
public abstract String Render();
}
Element:
public abstract class Element
{
public String Render(RenderStrategy strategy)
{
return strategy.Render();
}
}
my question is how should CompositeElement look like without the need of
RenderCompositeElementStrategy
I would do like this:
public interface IStrategy
{
string Render();
}
public class Element : IStrategy
{
public string Render() {
return "rendering for element";
}
}
public class CompositeElement : IStrategy
{
public string Render() {
return "rendering for composite element";
}
}
public class HTMLRenderer
{
private ISTrategy ele = new Element();
private IStrategy comp = new CompositeElement();
private IStrategy curr;
public HTMLREnderer(){
curr = ele; //i set default here to Element, but you can change it base on your need
}
public void RenderNow(){
Console.WriteLine(curr.Render());
//change your strategy accordingly to your need here, may be?
}
}
The code is simple enough to understand I hope.
I'm trying to use an interface type IColor in order to pass color objects to the ColorManager. I then want the ColorManager to pass this object to the IColor object as its own type, so the method overloads gets called.
However, it seems since it is being passed as the IColor type, C# will not implicity cast it into its complete type as either a BlueColor or GreenColor.
I hope this makes some sense to somebody on what I want to achieve. Is this possible in C#?
[Solution]
http://msdn.microsoft.com/en-us/library/dd264736.aspx
Overload Resolution with Arguments of Type dynamic
My code so far:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
namespace Example
{
public interface IColor
{
void CatchColor(IColor c);
}
public class BlueColor : IColor
{
public void CatchColor(IColor c)
{
}
}
public class GreenColor : IColor
{
public void CatchColor(BlueColor c)
{
Console.WriteLine("CAUGHT BLUE!");
}
public void CatchColor(GreenColor c)
{
Console.WriteLine("CAUGHT GREEN!");
}
public void CatchColor(IColor c)
{
Console.WriteLine("CAUGHT SOME COLOR!");
}
}
public class ColorManager
{
public void PassColor(IColor c)
{
// Don't use static type-checking
// Problem solved
dynamic AnyColor = c;
AnyColor.CatchColor(AnyColor);
}
public static void Main()
{
GreenColor G = new GreenColor();
new ColorManager().PassColor(G);
Console.ReadLine();
return;
}
}
}
One possiblity to tell the ColorManager class to use the correct type of the passed object is to use an abstract class, that already implements the CatchColor:
public abstract class IColor
{
// override in every class
public abstract void PrintColor();
// has the correct type passed with the interface
public void CatchColor(IColor c)
{
c.PrintColor();
}
}
Then the sub classes need to implement only PrintColor with the correct color:
public class BlueColor : IColor
{
public override void PrintColor()
{
Console.WriteLine("BLUE!");
}
}
public class GreenColor : IColor
{
public override void PrintColor()
{
Console.WriteLine("GREEN!");
}
}
The manager is the same:
public class ColorManager
{
public void PassColor(IColor c)
{
c.CatchColor(c);
}
}
It can be used like this:
GreenColor G = new GreenColor();
var cm = new ColorManager();
cm.PassColor(G);
cm.PassColor(new BlueColor());
The outputs is:
GREEN!
BLUE!
What you want is late method binding.
The downside to this is you have to add methods for each new type of color. The upside is you don't have to maintain a case statement or conditional logic.
See here for more detail:
Early and late binding
Edit: Here is a working example of this type of late-binding.
class Program {
static void Main(string[] args) {
//Declare instances
BaseClass myClass = new Class2();
BaseClass otherClass = new Class1();
//Invoke the action method which will match based on the BaseClass type
Action(myClass);
Action(otherClass);
Console.ReadLine();
}
public static void Action(BaseClass classType) {
//Remove the compile-time type so the runtime can select the method based on signature
dynamic aClass = classType;
ServiceMethod(aClass);
}
public static void ServiceMethod(dynamic input) {
Methods(input);
}
public static void Methods(Class1 classType) {
Console.WriteLine("Class1");
Debug.WriteLine("Class1");
}
public static void Methods(Class2 classtype) {
Console.WriteLine("Class2");
Debug.WriteLine("Class2");
}
public static void Methods(Class3 classType) {
Console.WriteLine("Class3");
Debug.WriteLine("Class3");
}
}
public abstract class BaseClass { //This could also be an interface
public Guid Id { get; set; }
public string Name { get; set; }
}
public class Class1 : BaseClass {
}
public class Class2 : BaseClass{
}
public class Class3 : BaseClass {
}
So you want something like:
public void CatchColor(Color c)
{
if (c is BlueColor)
CatchColor(c as BlueColor);
if (c is GreenColor)
CatchColor(c as GreenColor);
}
?