TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
john ranella
1.5k
191
5.7k
common property and methods between classes
Sep 11 2015 5:24 AM
Hi,
I have some classes that share between their methods and properties: for example class A call method of class B and both class must have common field/property
Common methods/property are several!
I thought of this approach
//------------------------------------------------------
// CLASS 'A'
//------------------------------------------------------
public class A
{
public A Instance{get{return this;}}
public IB b;
public float FieldA;
public void DoSomethingA()
{
FieldA = b.DoSomethingB ();
}
}
//------------------------------------------------------
// INTERFACE + CLASS 'B'
//------------------------------------------------------
public interface IB
{
B Instance{get;}
A a {get;set;}
float DoSomethingB();
}
public class B:IB
{
public B Instance{get{return this;}}
public A a {get;set;}
public virtual float DoSomethingB()
{
return a.FieldA * 0.5F;
}
}
//------------------------------------------------------
// CLASS B2
//------------------------------------------------------
public class B2:B
{
public override float DoSomethingB ()
{
return a.FieldA * 2.0F;
}
}
//------------------------------------------------------
// CLASS TEST
//------------------------------------------------------
public class test
{
public A a = new A();
public IB b;
public test (IB b)
{
this.b = b;
b.a = a.Instance;
a.b = b.Instance;
// other
}
}
public static void Main (string[] args)
{
test t = new test (new B());
t.a.FieldA = 5;
t.a.DoSomethingA();
Console.WriteLine (t.a.FieldA ); // return 2.5
test t1 = new test (new B2()); // return 10
t1.a.FieldA = 5;
t1.a.DoSomethingA();
Console.WriteLine (t1.a.FieldA );
}
Essentially in the class test pass the class instance A to the class B and vice versa (and thus also for future classes).
When i create a new instance of test i decide if use class B or B2 (trough interface).
This approach is correct or i'm in a wrong way?
Reply
Answers (
2
)
How to start windows service from winform on button click?
Using Application data class(local settings) in windows phon