Take the scenario
BaseA -> SubB -> SubSubC
Explanation: SubSubC class inherits SubB class. The SubB class inherits BaseA class
BaseA -> SubD -> SubSubE
Explanation: SubSubE class inherits SubD class. The SubB class inherits BaseA class
So..on..
So there are many class that has its grand parent class as BaseA . The BaseA class has some properties that are common to all the methods. ex: CustomerID, LastLogin, UniqueName etc.
This is how the class is designed in the service which I'm consuming.
My doubt is While calling the service methods, all the methods would expect a parameter of any SubSub class. Can anyone please tell me, is there any way if I could assign values to the properties of the BaseA in one place so that while creating the SubSub objects I did not need to fill the base properties each time?
I'm using C# as my language.
Code:
public class BaseA
{
public int CustomerId { get; set; }
public string UniqueName { get; set; }
}
public class SubB : BaseA
{
}
public class SubSubC : SubB
{
}
public class SubD : BaseA
{
}
public class SubSubE : SubD
{
}
public class MyMain
{
public void SendRequestToService1()
{
(new MyServiceObject()).ServiceMethod1(new SubSubC());
}
public void SendRequestToService2()
{
(new MyServiceObject()).ServiceMethod2(new SubSubE());
}
}
In the above code, in SendRequestToService1 and SendRequestToService2 , i need to initialise the base class properties CustomerId and UniqueName.
Ex:
(new SubSubC(){ CustomerId=2, UniqueName="XXBB" });
If there are many methods, I need to initialize these properties each time for their respective classes. Is there a way I can initialize the base properties CustomerId and UniqueName in one place so that the inheriting classes(SubSubC,SubSubE here) no need to initialize when their objects are created?
Are you looking for the following functionality?
//dummy class replacing the service object and it's methods
public class MyServiceObject
{
public void ServiceMethod1(SubSubC param)
{ }
public void ServiceMethod2(SubSubE param)
{ }
}
public class BaseA
{
public int CustomerId { get; set; }
public string UniqueName { get; set; }
}
public class SubB : BaseA
{
}
public class SubSubC : SubB
{
}
public class SubD : BaseA
{
}
public class SubSubE : SubD
{
}
public class MyMain
{
//declare the SubSub objects
//SubSubC subSubC;
//SubSubE subSubE;
BaseA baseA;
public MyMain()
{
//assign the values to each class in the MyMain contrsuctor
baseA = new BaseA { CustomerId = 2, UniqueName = "XXBB" };
}
public void SendRequestToService1()
{
var subSub=new SubSubC();
(new MyServiceObject()).ServiceMethod1(Initialize(subSub));
}
public void SendRequestToService2()
{
var subSub = new SubSubE();
(new MyServiceObject()).ServiceMethod2(Initialize(subSub));
}
private T Initialize<T>(T subSub) where T:BaseA
{
subSub.CustomerId = baseA.CustomerId;
subSub.UniqueName = baseA.UniqueName;
return subSub;
}
}
class Program
{
static void Main(string[] args)
{
MyMain myMain = new MyMain();
myMain.SendRequestToService1();
myMain.SendRequestToService2();
}
}
Are you asking about calling base constructors? If so:
class SubSubC : SubB
{
public object CProperty { get; private set; }
public SubSubC(object cProperty, string bProperty, int id) : base(bProperty, id)
{
CProperty = cProperty;
}
}
class SubB : BaseA
{
public string BProperty { get; private set; }
public SubB(string bProperty, int id) : base(id)
{
BProperty = bProperty;
}
}
class BaseA
{
public int ID { get; private set; }
public BaseA(int id)
{
ID = id;
}
}
Or are you asking about initializing objects in a method? If so (assume the setters are public in the following code, unlike in the preceding):
void SetSubSubCProperties(SubSubC c, object cProperty, string bProperty, int id)
{
c.CProperty = cProperty;
SetSubBProperties(c, bProperty, id);
}
void SetSubBProperties(SubB b, string bProperty, int id)
{
b.BProperty = bProperty;
SetBaseAProperties(b, id);
}
void SetBaseAProperties(BaseA a, int id)
{
a.ID = id;
}
Ok, Alex Filipovici's answer, it looks like you want to initialize an instance of a derived class by copying the base class properties from an instance of a different derived class. In that case, to reduce the duplication in Alex's answer, you can do this:
void Initialize(BaseA source, BaseA target)
{
target.CustomerID = source.CustomerID;
target.UniqueName = source.UniqueName;
}
Then, to modify his example:
public void SendRequestToService1()
{
var subSub = new SubSubC();
Initialize(this.baseA, subSub);
(new MyServiceObject()).ServiceMethod1(subSub);
}
public void SendRequestToService2()
{
var subSub = new SubSubE();
Initialize(this.baseA, subSub);
(new MyServiceObject()).ServiceMethod2(subSub);
}
Not sure I understand your question.
public class A {
public int ID { get; set; }
}
public class B : A {
}
you can do B b = new B() and then b.ID = 12.
Or, if you have a method that gets a parameter of type A in your service you can change the value in the same way.
public void doSomething(A a) {
a.ID = 12;
}
and call the method with instances of B - doSomething(new B())
Related
Suppose I have two classes and both contain the same fields
Class A
{
public string Name { get; set; }
public int Designaton { get; set; }
}
Class B
{
public string Name { get; set; }
public int Designation { get; set; }
}
And I have one interface and two classes which are inherited from interface
public interface IDeprt
{
object BindData();
}
And two extractor classes:
public classAItem : IDeprt
{
public object BindData()
{
return new A()
{
// mapping operation
}
}
}
public classBItem : IDeprt
{
public object BindData()
{
return new B()
{
//same mapping operation
}
}
}
My question, how can I implement this in generic way using <T> .
Both classes are doing same operation only return type change. If I am doing in the above way there is lot of duplication of code.
Make your ITem interface and also BindData generic make them use the same generic parameter.
public interface IItem<T>
{
T BindData();
}
Then implement the subclasses like below :
public class AItem : ITem<A>
{
public A BindData(){
return new A(){
// mapping operation
}
}
}
public class BItem : ITem<B>
{
public B BindData(){
return new B(){
//same mapping operation
}
}
}
Edit : As the question evolves.
Make a shared base class for A and B classes.
public abstract class CommonItem
{
public string Name { get; set; }
public int Designaton { get; set; }
}
class A : CommonItem
{
}
class B : CommonItem
{
}
Then make class with a method that accepts a generic parameter with new and CommonItem constraints.
public class Binder
{
public T BindData<T>() where T: CommonItem, new()
{
return new T()
{
// you can access the properties defined in ICommonItem
}
}
}
Usage :
var binder = new Binder();
var boundA = binder.BindData<A>();
var boundB = binder.BindData<B>();
I have some problem I can not resolve.
I have a class GlobalTest derived from GlobalObjectImpl:
public class GlobalTest : GlobalObjectImpl
{
public string LastProcessDay { get; set; }
}
It was called from this:
var global = GlobalTest.Get<GlobalTest>();
The GlobalObjectImpl is declared like this:
public abstract class GlobalObjectImpl
{
public bool Save()
{
return DataStore.SaveGlobal(this);
}
public static T Get<T>() where T : GlobalObjectImpl
{
return DataStore.GetGlobal<T>();
}
}
I want to get my LastProceedDate like this:
var global = GlobalTest.Get();
But it fails.
You can make your abstract class generic like the following:
public abstract class Base<T>
{
public static T Get() => throw new NotImplementedException();
}
public class Derived : Base<Derived> { }
And then just call Get
var foo = Derived.Get();
I all, big thank to you, i have succesfully implemented my class
My Abstract Class
public abstract class GlobalTreeObjectImpl<T>
{
public bool Save()
{
return NeoStore.SaveGlobal(this);
}
public static T Get() => NeoStore.GetGlobal<T>();
}
}
Class use abstract class
public class GlobalTest : GlobalTreeObjectImpl<GlobalAntai>
{
public string LastProcessDay { get; set; }
}
Usage of this on my code
var global = GlobalTest.Get();
LoggerManager.LogInfo($"Global LastProcessDay : {global.LastProcessDay} - {DateTime.UtcNow}");
global.LastProcessDay = DateTime.Now.AddDays(10).ToString("yyyy-MM-ddThhh:mmm:ssZ");
global.Save();
global = GlobalTest.Get();
LoggerManager.LogInfo($"Global LastProcessDay : {global.LastProcessDay} - {DateTime.UtcNow}");
I have the following classes:
//some base class
public abstract class MyObject<T>{
public static T FromObject(object anotherObject){
var t = Activator.CreateInstance<T>();
// some reflection logic here
return t;
}
}
public class Product: MyObject<Product>{
}
public class ProductCart: MyObject<ProductCart>{
public ICollection<Product> Products{get;set;}
}
public class Basket: ProductCart{
public int BasketId{get;set;}
}
public class Order: ProductCart{
public int OrderId{get;set;}
}
So now I could build my model like this:
var products = serviceContext.Products.Select(Product.FromObject).ToList(); // no problem here
var basket = Basket.FromObject(serviceContext.Basket); // problem is here - instance of ProductCart is returned
var order = Order.FromObject(serviceContext.Order); // same problem, instance of ProductCart
Is there a way somehow to solve it and get converted Basket and Order instead of base ProductCart?
The goal is:
var basket = Basket.FromObject(serviceContext.Basket); // return instance of Basket inherited from ProductCart
Thanks for helping.
If you can change the class definitions, you can pass along the type to ProductCart, like so:
public class ProductCart<T> : MyObject<T> { }
public class Basket : ProductCart<Basket> { }
public class Order : ProductCart<Order> {}
In your definition you tell Basket.FromObject to explicitly return ProductCarts (by inheriting from MyObject<ProductCart>).
And if you're unable to change the inherit tree, you can choose to hide the original method (or place it in a factory):
public class Basket : ProductCart
{
public int BasketId { get; set; }
public Basket FromObject(object anotherObject)
{
return MyObject<Basket>.FromObject(anotherObject);
}
}
That's because Basket is a MyObject<ProductCart>, and not a MyObject<Basket>.
If you don't want to redefine your hierarchy, you should define the return type of the static method according to the object you pass, like in this example:
using System;
public abstract class MyObject<T> {
public static TOtherObject FromObject<TOtherObject>(TOtherObject anotherObject) where TOtherObject : MyObject<T> {
var newOtherTypeInstance = Activator.CreateInstance<TOtherObject>();
// some reflection logic here
return newOtherTypeInstance;
}
}
public class ProductCart : MyObject<ProductCart> {
}
public class Basket : ProductCart {
public int BasketId { get; set; }
}
public class Order : ProductCart {
public int OrderId { get; set; }
}
class Program {
static void Main(string[] args) {
Order o = new Order();
var basket = Basket.FromObject(o);
}
}
Of course, at this point the actual implementation of the comment "some reflection logic here" could get much more complicated :)
How do I define a factory whose implementations may accept different numbers of parameters?
public abstract class CarFactory
{
public abstract void countStuff(??); //not sure how to define this
}
I would like the factory to be able to create different objects like:
public class BMW : CarFactory
{
public override void countStuff(param1, param2) {}
}
public class Ford : CarFactory
{
public override void countStuff(param1) {}
}
Not sure if "countStuff" should be a factory responsibility, but you could get something similar this way:
public interface ICountParam {}
public class BmwParam : ICountParam
{
public BmwParam(string a)
{
A = a;
}
public string A { get; set; }
}
public class FordParam : ICountParam
{
public FordParam(string a, string b)
{
A = a;
B = b;
}
public string A { get; set; }
public string B { get; set; }
}
public interface ICarFactory<in T> where T : ICountParam
{
void CountStuff(T param);
}
public class BMW : ICarFactory<BmwParam>
{
public void CountStuff(BmwParam param) { }
}
public class Ford : ICarFactory<FordParam>
{
public void CountStuff(FordParam param) { }
}
Usage:
bmw.CountStuff(new BmwParam("A"));
ford.CountStuff(new FordParam("A", "B"));
I trying to figure out how to write a class where the base class would supply the accessor functions and then the instanced class only needs to supply the values.
Something like this:
public interface IBaseClass
{
int GetHandlerID();
}
public abstract class AbstractClass : IBaseClass
{
private int HandlerID;
public virtual int GetHandlerID()
{
return (this.HandlerID);
}
}
public class MyClass : AbstractClass
{
int HandlerID = 1;
}
class Program
{
static void Main(string[] args)
{
MyClass newClass = new MyClass();
Console.WriteLine("HandlerID: {0}"), newClass.GetHandlerID() );
}
}
It doesn't work this way because the class is going to read the HandlerID in the AbstractClass instead of the MyClass variable. Using Virtual or Abstract isn't valid for variables, so I'm not sure how to do this other than having to implement properties every time a new class is derived.
What I'm trying to do is supply an interface for people to build their own plug-in class and it would use the accessor methods that are supplied with the base class. I don't want to have to implement the same property method every time I create a new instance of the class.
I figured out a way to do what I wanted. This way I can have default getters/setters in the base class and not have to create those in each definition that uses the base. It's not quite what I was looking for, but it'll work.
public abstract class AbstractClass : IBaseClass
{
private int m_HandlerID = 0;
public int HandlerID
{
get { return (this.m_HandlerID); }
set { this.m_HandlerID = value; }
}
private string m_HandlerDescription = "undefined";
public string HandlerDescription
{
get { return this.m_HandlerDescription; }
set { this.m_HandlerDescription = value; }
}
}
public class MyClass: AbstractClass
{
public MyClass()
{
HandlerID = 1;
HandlerDescription = "MyClass";
}
}
class Program
{
static void Main(string[] args)
{
MyClass newClass = new MyClass();
Console.WriteLine("Handler: {0}[{1}]", newClass.HandlerDescription, newClass.HandlerID);
}
}
public abstract class AbstractClass : IBaseClass
{
public AbstractClass(int handlerId)
{
this.HandlerId = handlerId;
}
public int GetHandlerID()
{
return (this.HandlerID);
}
}
public class MyClass : AbstractClass
{
public MyClass():base(1)//specific handler id
}
How about passing the value through the base constructor
The derived class needs able to access the HandlerID to ovewrite it, so you'll need to change it in the abstract class from 'private' to 'protected'.
public interface IBaseClass
{
int GetHandlerID();
}
public abstract class AbstractClass : IBaseClass
{
protected virtual int HandlerID { get; set; }
public virtual int GetHandlerID()
{
return (HandlerID);
}
}
public class MyClass : AbstractClass
{
private int _handlerID = 1;
protected override int HandlerID { get { return _handlerID; } set { _handlerID = value; } }
}
private static void Main(string[] args)
{
var newClass = new MyClass();
Console.WriteLine("HandlerID: {0}", newClass.GetHandlerID());
Console.ReadKey();
}