Is there a way know which class has called a function in another class.
Eg:
public class A
{
public static string Aa = "test";
public void test()
{
B.testB();
}
}
public class B
{
public static void testB()
{
string Bb = A.Aa;
}
}
In the above example, i know the class A function has called the function in class B. But if there are many classes which will call the function in class B and all of those classes will have variable Aa in common, so how can i read its value and assign it to Bb. So in simple
string Bb = CalledClassName.Aa;
You could use the CallerMemberNameAttribute that was added with .NET 4.5. This will only get you the member name though:
public void SomeMethod ()
{
OtherMethod();
}
public void OtherMethod ([CallerMemberName] string memberName = null)
{
Console.WriteLine(memberName);
}
The attribute will fill the optional parameter at compile time, so it will actually call OtherMethod("SomeMethod").
You could also use a combination of accessing the stack trace and using reflection to read the Aa property of the type of the calling method. Note that this accesses debugging information, and is very vulnerable to changes in your code. It also has a bad performance, so you should avoid it. But just to show you how to use it:
public static void testB()
{
StackTrace stackTrace = new StackTrace();
Type callingType = stackTrace.GetFrame(1).GetMethod().DeclaringType;
FieldInfo field = callingType.GetField("Aa", BindingFlags.Public | BindingFlags.Static);
string Bb = (string) field.GetValue(null);
Console.WriteLine(Bb);
}
Use an interface, pass that in:
public interface AaInterface {
public string GetAa();
}
public class A : AaInterface
{
public static string Aa = "test";
public GetAa() { return Aa; }
public void test()
{
B.testB(this);
}
}
public class B
{
public static void testB(AaInterface pAa)
{
string Bb = pAa.GetAa();
}
}
I guess you are looking for something different than you are asking.
You should pass the instance of A to your method. All calling methods should pass the instance based on an interface. In that interface you put the properties and methods you want to share. In that way you can call the 'same' method for every passed instance.
public interface ISomeInterface
{
string Aa {get;}
}
public class A : ISomeInterface
{
public string Aa {get { return "a"; } }
}
Then you can pass it to this method:
public static void testB(ISomeInterface something)
{
string Bb = something.Aa;
}
Note that in this case, Aa is not allowed to be static. You could wrap that static in an instance property though.
If i understood your question correctly then you can pass a reference to a class instance in method as parameter then use 'is' operator to check its type:
public class A
{
public static string Aa = "test";
public void test(object calledClass)
{
if(calledClass is B) Aa = calledClass.Bb;
}
}
When you call this static method from class B just put :
A.Test(this)
P.S.
This is just an example of logic that you can use to achieve what you want
I geuss you can do something like this:
public class A {
public void test() {
B.testB(this);
}
}
public class B {
public static void testB(object sender) {
String className = sender.GetType().Name;
}
}
//To call
A a = new A();
a.test();
Related
What I have is:
public static class IDs {
public static string someID { get; set; }
static IDs() {
log.info(someID);
// use someID here
}
}
public class otherClass {
public void otherMethod(string sym) {
IDs.someID = sym;
}
}
and then using an instance of otherClass like this:
otherClassInstance.otherMethod("someStringSymbol");
I dont have any build errors, but log.info(someID); is printing null.
I was expecting it to be someStringSymbol.
This is because the static constructor is called automatically before the first instance is created or any static members are referenced..
This means that when an instance of otherClass invokes IDs.someID = sym; the first operation that gets executed is the static constructor, i.e. the code inside static IDs().
At this point the static variable has not yet been initialized, and you are basically executing log.info(null);.
After the static constructor completes, the variable is initialized, so you should be able to see its value inside otherMethod, after the first reference of IDs.
Given the OP's requirement:
I want to use the value passed in someID in a switch statement
The solution could be to simply execute a static method whenever a new value is set, with the help of explicit getters and setters:
public static class IDs
{
private static string _someID; // backing field
public static string SomeID
{
get { return _someID; }
set
{
_someID = value;
DoSomethingWithSomeID();
}
}
private static DoSomethingWithSomeID()
{
// Use SomeID here.
switch (IDs.SomeID)
{
...
}
}
}
public class OtherClass
{
public void OtherMethod(string sym)
{
// This will set a new value to the property
// and invoke DoSomethingWithSomeID.
IDs.SomeID = sym;
}
}
DoSomethingWithSomeID will be invoked every time someone sets a new value to SomeID.
I dont think what you are trying to do is suited to static classes. I would try the following
public class IDs{
public string someID{ get; set; }
public IDs(string someId){
this.someID = someId;
log.info(this.someID);
//use someID here
}
}
pulic class otherClass{
public otherMethod(string sym){
IDs id = new IDs(sym);
}
}
public class anotherClass{
//access instance of otherClass in wrp and call otherMethod()
wrp.otherMethod("someStringSymbol")
}
I'm currently having trouble and I have no clue how to fix it.
I have 2 classes:
class A
{
public string MyParam { get; set; }
}
class B : A
{
public new string MyParam { get { return base.MyParam != null ? base.MyParam.Substring(1) : null; } }
}
When I try to access the B.MyParam it works when I have a the correct type, but in most of my methods I have a generic type
with :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
public class A
{
public string MyParam { get; set; }
}
public class B : A
{
public new string MyParam
{
get { return base.MyParam != null ? base.MyParam.Substring(1) : null; }
}
}
public static void MyMethod<T>(T variable) where T : A
{
Console.WriteLine(variable.MyParam);//this print hello
Console.WriteLine((variable as B).MyParam);//this print ello (exactly what i want)
Console.WriteLine(typeof(T)); // this print ConsoleApplication1.Program+A
Console.WriteLine(variable.GetType()); // this print ConsoleApplication1.Program+B
// so i need something like that
Console.WriteLine((variable as variable.GetType()).MyParam); // this line is invalid
}
static void Main(string[] args)
{
A a = new B();
a.MyParam = "Hello";
Console.WriteLine(a.GetType());
MyMethod(a);
Console.ReadKey();
}
}
}
Is there a way to do it?
Thank you in advance.
EDIT: it seems that what i want is :
dynamic variable2 = Convert.ChangeType(variable, variable.GetType());
Console.WriteLine(variable2.MyParam);
Your code doesn´t make any sense. If A inherits from B you´ll need A to override the base-implementation for your property. So I´ll assume you should rethink your inheritance-chain.
You can use override for this. Thus when your variable-parameter is of your base-class (I renamed that to A) you´re calling the base-method, if it´s a derived instance (here B) you´re calling the override:
class A
{
public virtual string MyParam { get; }
}
class B : A // note here that B derives from A, not the other way round
{
public override string MyParam
{
get { return base.MyParam != null ? base.MyParam.Substring(1) : null; },
set { ... }
}
}
EDIT: While new intrduces a new member which (accidentally) has the same name (and signature) as the base-member it effectivly hides the base-member. Thus you effectivly have two members. Your only way to indicate which member should be used is by casting your instance to the desired class from which you need the implementation. However this somehow breaks the purpose of generics as the generic member has to know the exact types that are possible for the type-parameter.
Anyway this seems like broken design to me, as you´re actually creating a new member which has another meaning. So you should also give it a new name.
Based on your generic method, I think all you need is an interface.
public interface IMyParam
{
string MyParam { get; set; }
}
Your classes.
class A : IMyParam
{
public virtual string MyParam { get; set; }
}
class B : A
{
public override string MyParam
{
get { return base.MyParam != null ? base.MyParam.Substring(1) : null; }
}
}
And your method, won't need to be generic.
public void MyMethod(IMyParam variable)
{
// Your logic here, for example.
Console.WriteLine(variable.MyParam);
}
Calling your method.
A a = new A();
a.MyParam = "Hello";
B b = new B();
b.MyParam = "Hello";
A ab = new B();
ab.MyParam = "Hello";
MyMethod(a); // Prints Hello
MyMethod(b); // Prints ello
MyMethod(ab); // Prints ello
Below is the sample code
public class class1
{
public static void emp(string name)
{
.....
value = (value that is returned)
}
}
public class class2
{
public static void studen(string division)
{
...
}
}
This is how i want to use. class2.studen(value);
Here i need to pass the value that is returned from class1 to the string division of class2.
Any help would be appreciated.
Here function emp and studen are in different class files.
As hatchet mentioned, you're not getting a result from class1. There's a lot of info missing from your post but based on what I think you're trying to do, try like this:
public class class1
{
public static string value { get; set; } // use the proper type here if it's not a string
public static void emp(string name)
{
.....
this.value = (value that is returned)
}
}
public class class2
{
public static void studen(string division)
{
class1.emp("Hello");
string class2Var = class1.value; // class2Var will now be "Hello"
}
}
I have a ton of methods like this:
public UIPCompanyButton AddCompanyButton (string name, Company company, UIEventListener.VoidDelegate methodToCall, GameObject contents)
{
return UIPCompanyButton.Create (name, company, methodToCall, contents);
}
that I'd like to replace with a single method like this:
public T AddButton<T,K>(string name, K item, UIEventListener.VoidDelegate methodToCall, GameObject contents) where T:UIPMenuButton
{
return T.Create(name, item, methodToCall, contents);
}
which obviously doesn't work at the T.Create part. Is there a certain syntax I need to do this?
I'm also open to a different method with the same result: a single method that takes in a derived menuButton and creates the right one with the right class of "item".
No, you can't call static methods on generic types - not without reflection. Aside from anything else, there's no way of constraining a generic type to have specific static members. The closest to that is the parameterless constructor constraint.
What you want is a factory to create your objects. Here is a small working example. It might not be the best way to implement a factory pattern, but it should get you going.
For a more in depth example and explanation, see this page.
public class Button {
public string Whatever { get; set; }
public Button() {
Whatever = "Hello, world!";
}
}
public interface IAddButton {
Button CreateButton();
}
public class ClassToMakeButtonFor1 {
public static void RegisterMe() {
ButtonFactory.Register(typeof(ClassToMakeButtonFor1), new ButtonFactory1());
}
}
public class ButtonFactory1 : IAddButton {
public Button CreateButton() {
return new Button();
}
}
public class ClassToMakeButtonFor2 {
public static void RegisterMe() {
ButtonFactory.Register(typeof(ClassToMakeButtonFor2), new ButtonFactory2());
}
}
public class ButtonFactory2 : IAddButton {
public Button CreateButton() {
var b = new Button { Whatever = "Goodbye!" };
return b;
}
}
public static class ButtonFactory {
private static Dictionary<Type, IAddButton> FactoryMap = new Dictionary<Type, IAddButton>();
public static void Register(Type type, IAddButton factoryClass) {
FactoryMap[type] = factoryClass;
}
public static Button MakeMeAButton<T>() where T : class {
return FactoryMap[typeof(T)].CreateButton();
}
}
internal class Program {
private static void Main(string[] args) {
ClassToMakeButtonFor1.RegisterMe();
ClassToMakeButtonFor2.RegisterMe();
Button b = ButtonFactory.MakeMeAButton<ClassToMakeButtonFor1>();
Console.WriteLine(b.Whatever);
b = ButtonFactory.MakeMeAButton<ClassToMakeButtonFor2>();
Console.WriteLine(b.Whatever);
Console.ReadLine();
}
}
What you could consider is to have some interface (e.g. ICreator) that defines a Create method you want to call.
Then you would constrain your type parameter to types that implement the interface ( where T : ICreator).
Then you would call the method on an instance, not a static method. So in your case maybe you could call item.Create(...).
Makes any sense for your case?
It sounds like you might be able to make your Button class generic. Depending on how much logic lives in each of these derived classes, this may not work for you.
class Button<T>
{
public T Item { get; private set; }
public Button(string name, T item, ...)
{
// Constructor code
}
}
// Helper class for creation
static class Button
{
public static Button<T> Create<T>(string name, T item, ...)
{
return new Button<T>(name, item, ...);
}
}
Then, to use this:
Button<Company> button = Button.Create("Name", company, ...);
Can somone explain why I get this error on this code?
Error 1 The type
'ConsoleApplication1.TestClass'
already contains a definition for
'IsThisOK'
class TestClass
{
public bool IsThisOK { get; set; }
public static bool IsThisOK(string str)
{
return true;
}
public static void Test()
{
TestClass c = new TestClass();
c.IsThisOK = IsThisOK("Hello");
}
}
You're trying to define a property and a method with the same name. While you can have multiple methods that override each other (with different argument lists), you cannot have a property and a method that share the same name
You've declared IsThisOK twice, at line 3 and line 5 (property and static function).
Try to imagine how could the compiler could figure out to which you are referring later on?
Because you cannot provide same name to a function and a Property.
You cannot overload function with property.
You can use it in this way:
class TestClass
{
public bool IsThisOK { get; set; }
public static bool isThisOK(string str)
{
return true;
}
public static void Test()
{
TestClass c = new TestClass();
c.IsThisOK = isThisOK("Hello");
}
}
As other pointed out, you cannot have a method and a property with the same name.
However, you can more or less work around this by using an extension method if you like:
static class TestClassExtension
{
public static bool IsThisOK(this TestClass, string str)
{
return true;
}
}
class TestClass
{
public bool IsThisOK { get; set; }
public static void Test()
{
TestClass c = new TestClass();
c.IsThisOK = this.IsThisOK("Hello");
}
}