This should be a very simple solution for the avid C# developer. I am looking to change the value of a string within a class, so within a thread, the string can change without me doing anything. Here is a small example of what I mean, simplified, but you should get the idea.
class A_CLass
{
string keptString;
void keepString( ref string theString )
{
keptString = theString;
}
// This will get called when the thread is triggered
void changeString( string theString )
{
keptString = theString;
}
}
void f1()
{
A_Class a = new A_Class();
string base_string = "asdf";
a.keepString( ref base_string );
...
// Thread is signaled
...
// Now base_string should be "fdsa"
}
void threadedFunction()
{
// When the thread is triggered ...
a.changeString( "fdsa" );
}
Basically I want to keep a reference of 'base_string' in the A_Class, so threaded methods can change the value, and within f1(), I can see the changed value, in this case "fdsa".
Thanks!
Use a StringBuilder for this purpose.
Represents a mutable string of characters.
It looks like you are wanting to store a reference to the reference (like a pointer to a pointer). One way to do something like this would be to pass a method that sets the string into your class like this:
class A_Class
{
Action<string> setter;
void storeSetter( Action<string> setter )
{
this.setter = setter;
}
void callSetter( string str )
{
setter(str);
}
}
Then pass in a lambda that sets the string like:
public class OtherClass
{
private string someString;
private void test()
{
var a = new A_Class();
a.keepString((s)=>{someString = s;});
}
}
Once your class has this string setting method, you can call the method to set the string.
You'll have to use an intermediate wrapper class:
public class Wrapper<T> // generic, so can be used with any type
{
public T Value { get; set; }
public Wrapper(T val) { Value = val; }
}
class A_CLass
{
Wrapper<string> keptString;
void keepString(string theString)
{
keptString = new Wrapper<string>(theString);
}
void changeString(string theString)
{
keptString.Value = theString;
}
}
class A_Class
{
Ref<string> link;
void A_Class( Ref<string> link)
{
this.link= link;
}
void somefunction( string str )
{
if(link.Value.Length > 2)
link.Value = str;
}
}
public class Ref<T>
{
private Func<T> getter;
private Action<T> setter;
public Ref(Func<T> getter, Action<T> setter)
{
this.getter = getter;
this.setter = setter;
}
public T Value
{
get
{
return getter();
}
set
{
setter(value);
}
}
}
Related
This is a pretty beginner question but I'm stumped and I can't figure out how to get what I want from this. I have my first class that obtains information (database/textfile/whatever) but I want it to relay that information into Class2.
For instance, the first:
public class Class1
{
private int first;
private string firstString;
private bool isTrue;
public void SomeMethod()
{
first = 1;
firstString = "FirstString";
isTrue = true;
}
}
Here SomeMethod sets all the attributes that I need to pass into Class2.
ClassTwo looks like
public class Class2
{
private int first;
private string FirstString;
private bool isTrue;
private int second;
private string SecondString;
private bool isFalse;
public void SomeOtherMethod()
{
}
}
Here what I want is for SomeOtherMethod() to set the first set of attributes with the values that were set in Class1's SomeMethod(). So that I can create an object of type Class2 and add what I want to it.
As some other commentators stated, you really should reuse your data definitions. Something like this can get you started:
public class Class1
{
private int _myInt;
private string _myString;
private bool _myBool;
public void SomeMethod()
{
_myInt = 1;
_myString = "FirstString";
_myBool = true;
}
}
public Class2
{
private Class1 _first = new Class1();
private Class1 _second = new Class1();
public void SetFirst(Class1 obj)
{
_first = obj;
}
}
and then use the classes like this:
Class1 c1 = new Class1();
Class2 c2 = new Class2();
c1.SomeMethod();
c2.SetFirst(c1);
You have to define get accessors for the properties of Class1 because they are all unreachable from outside the class and Class2 needs to use their values. Defining public properties with get accessors can be useful:
private int first;
public int First
{
get
{
return first;
}
}
Having every property in Class1 defined like this, you can access the values. After calling SomeMethod, two objects' properties can be equalized in two simple ways (See also: Signatures and overloading):
public void SomeOtherMethod()
{
Class1 tempClass = new Class1();
tempClass.SomeMethod();
this.first = tempClass.first;
this.FirstString = tempClass.firstString;
this.isTrue = tempClass.isTrue;
}
public void SomeOtherMethod(Class1 myClass) // Overloaded method
{
this.first = myClass.first;
this.FirstString = myClass.firstString;
this.isTrue = myClass.isTrue;
}
Even though the techniques above seem like to be what you asked for, the best is to initialize a class's properties using constructors. This way, you don't have to call SomeMethod each time you create a Class1 object, and you can also set its default values whenever a new one is created. Also, giving more general names to the properties will save you from duplicates. I write some code to provide you an understandable syntax that will prevent future problems of non-accessibility and repetition.
public class Class1
{
private int number;
public int Number
{
get { return number; }
}
private string name;
public string Name
{
get { return name; }
}
private bool isTrue;
public bool IsTrue
{
get { return isTrue; }
}
public Class1()
{
number = 1;
name = "FirstString";
isTrue = true;
}
public Class1(int value1, string value2, bool value3)
{
number = value1;
name = value2;
isTrue = value3;
}
}
public class Class2
{
private Class1 firstClass;
private Class1 secondClass;
public Class2()
{
firstClass = new Class1();
secondClass = new Class1(2, "SecondString", false);
}
}
If you're going to define many Class1 objects in Class2, then a solution such as an array or a list becomes must. I'll give a short example, see MSDN List page.
private List<Class1> class1List = new List<Class1>();
class1List.Add(new Class1());
class1List.Add(new Class1(2, "SecondString", false));
I'm trying to expose an API such that, I do the following
RegisterCallback<T>(Action<T> func)
{
someObj.FuncPointer = func;
}
Later on, I call func(obj) .. and the obj is of type T that the user said.
More concrete example:
var callbackRegistrar = new CBRegistrar();
callbackRegistrar.RegisterCallback<ISomeClass>(SomeFunc);
public static void SomeFunc(ISomeClass data)
{
//
}
EDIT: So I may not have been clear, so I'll add more code:
I want to make only "one" object of CBRegistrar, and connect it with many Callbacks, as such:
var callbackRegistrar = new CBRegistrar();
callbackRegistrar.RegisterCallback<ISomeClass>(SomeFunc);
callbackRegistrar.RegisterCallback<ISomeOtherClass>(SomeFunc2);
...
In fact the above code is called by reflecting over a directory of plugins.
The user puts this in their code -->
public static void SomeFunc(ISomeClass data)
{
//
}
public static void SumFunc2(ISomeOtherClass data)
{
//
}
It looks to me as if this is not possible using Generics, etc. What it looks like I might have to do is make an interface called IPlugin or something, and ask the user to do this ..
[PluginIdentifier(typeof(ISomeClass))]
public static void SomeFunc(IPluginData data)
{
var castedStuff = data as ISomeClass; // ISomeClass inherits from IPluginData
}
Seems like asking the user to do stuff that we should take care of, but anyway ...
You need a Action<T> func to store it in. There is a semantic check to make here: if someone calls RegisterCallback twice (with different values), do you want to replace the callback, or keep both ? Assuming the latter, someObj probably wants an event (indeed, this entire API could be exposed as an event), so - in the someObj class:
public event Action<T> FuncPointer;
private void InvokeCallback(T data) {
var handler = FuncPointer;
if(handler != null) handler(data);
}
Noting that RegisterCallback could be replaced entirely, still keeping the data on obj:
public event Action<T> Completed {
add { obj.FuncPointer += value; }
remove { obj.FuncPointer -= value; }
}
Then usage would be:
var callbackRegistrar = new CBRegistrar();
callbackRegistrar.Completed += SomeFunc;
Callback functions are not much used in C#. They've been replaced by events which are more elegant and easier to work with.
class CBRegistrar
{
public delegate void ActionRequiredEventHandler(object sender, ISomeClass e);
public event ActionRequiredEventHandler ActionRequired;
void RaiseActionRequiredEvent(ISomeClass parm)
{
if ( ActionRequired != null)
{
ActionRequired(this, parm);
}
}
}
class APIConsumer
{
var callbackRegistrar = new CBRegistrar();
public APIConsumer()
{
callbackRegistrar.ActionRequired += SomeFunc;
}
public void SomeFunc(object sender, ISomeClass data)
{
}
}
If you still want to use Callbacks, you can use Delegates which are more or less function pointer.
The CBRegistrar will need to be generic (if it's OK to keep a single callback type) or it can do some internal casting (if several callback types need to be registered).
public class CBRegistrar<T>
{
private Action<T> callback;
private Dictionary<Type, object> callbackMap;
public CBRegistrar()
{
this.callbackMap = new Dictionary<Type, object>();
}
public void RegisterCallback(Action<T> func)
{
this.callback = func;
}
public void RegisterGenericCallback<U>(Action<U> func)
{
this.callbackMap[typeof(U)] = func;
}
public Action<U> GetCallback<U>()
{
return this.callbackMap[typeof(U)] as Action<U>;
}
}
public interface ISomeClass
{
string GetName();
}
public class SomeClass : ISomeClass
{
public string GetName()
{
return this.GetType().Name;
}
}
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
var callbackRegistrar = new CBRegistrar<ISomeClass>();
callbackRegistrar.RegisterCallback(SomeFunc);
callbackRegistrar.RegisterGenericCallback<ISomeClass>(SomeFunc);
var someone = new SomeClass();
callbackRegistrar.GetCallback<ISomeClass>()(someone);
}
public static void SomeFunc(ISomeClass data)
{
// Do something
Console.WriteLine(data.GetName());
}
}
}
For example, I have a static class that contain all default methods. What if I want to generate a properties and simultaneously generate a default static method---
static class Default
{
//Auto-Generated
static int DEFAULT_foo1()
{
//Do something
}
static float DEFAULT_var2
{
//Do something
}
}
class Other
{
//Code-Snippet
int var1
{
get
{
return Default.DEFAULT_var1();
}
}
float var2
{
get
{
return Default.DEFAULT_var2();
}
}
}
I think standard inheritance be a good solution.
class OtherBase
{
//Code-Snippet
int var1
{
get
{
return Default.DEFAULT_var1();
}
}
float var2
{
get
{
return Default.DEFAULT_var2();
}
}
}
Derived class:
class Other : OtherBase
{
}
Change the class Default to be a singleton instead of being static. Now you can implement the method as well as the property in the same class with a code snippet. Other classes can derive from Default and inherit the properties automatically.
class Default
{
public static readonly Default Instance = new Default();
protected Default ()
{
}
public static int DoFoo1()
{
//Do something
}
public int Foo1 { get { return DoFoo1(); } }
public static float DoVar2
{
//Do something
}
public float Var2 { get { return DoVar2(); } }
}
class Other : Default
{
// Inherits Foo1 and Var2 automatically
}
Use of Default and Other
int x = Default.DoFoo1();
int y = Default.Instance.Foo1;
Other other = new Other();
int z = other.Foo1;
I have a class with a method in which a string will be passed. That method will do some things to that string and it then passes the string to a certain object which can do other things with the string.
So it basically looks like this:
class Main
{
public Main()
{
strClass str = new strClass(this);
}
public function handler ( )
{
console.log("No string is passed yet, but this method is called from receiveData()");
}
}
class strClass
{
object handler;
public strClass ( handler )
{
// save the object
this.handler = handler;
}
public receiveData ( string str )
{
// This method does some stuff with the string
// And it then passes it on to the supplied object (handler) which will do
// the rest of the processing
// I'm calling the "handler" method in the object which got passed in the
// constructor
Type thisType = this.handler.GetType();
MethodInfo theMethod = thisType.GetMethod("handler");
theMethod.Invoke(this.handler, null);
}
}
Now this code works good, with the reflection stuff. But i was wondering, shouldn't this be possible (and maybe even better?) with delegates?? If so, how can i implement this by using a delegate instead?
Couldn't you use interfaces instead:
interface IStringHandler {
void HandleString(string s);
}
class strClass
{
IStringHandler handler = null;
public strClass(IStringHandler handler)
{
this.handler = handler;
}
public void ReceiveData(string s)
{
handler.HandleString(s);
}
}
class Main : IStringHandler
{
// Your code
}
A delegate is a better option here.
class Main
{
public Main()
{
StrClass str = new StrClass(this.Handler);
}
public void Handler ( )
{
//called from recieve data
}
}
class StrClass
{
readonly Action _handler;
public StrClass ( Action callback)
{
// save the object
this._handler = callback;
}
public void receiveData( string str )
{
this._handler();
}
}
You can do it with an Action like this:
class Main
{
public Main()
{
strClass str = new strClass(newString =>
{
console.log("This string I got back: " + newString);
});
}
}
class strClass
{
Action<string> callback;
public strClass (Action<string> callback)
{
// save the action
this.callback = callback;
}
public receiveData ( string str )
{
// Do something with the string
callback(str);
}
}
Even nicer than using delegates whould be using the
Chain of Responsibility design pattern, which does exactly what you need :).
Firstly, if you must call an unknown method by name, use dynamic - it is heavily optimised for this (although still not a great idea):
((dynamic)handler).handler(); // but please don't use this! see below
However, I would instead look at either an Action<string> (or maybe Func<string,string>), or an interface with a known method on it.
Basically, you want to change how your StrClass object react to data begin received. Sounds like events to me.
something like this, where you have handling methods both in the Main and in a generic HandlerObject:
class StrClass : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = null;
public void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
PropertyChanged(this, e);
}
private string receivedString;
public string ReceivedString
{
get;
set
{
string oldStr = receivedString;
receivedString = value;
PropertyChanged(receivedString, new PropertyChangedEventArgs("ReceivedString"));
}
}
public void receiveData(string str)
{
//event fires here
ReceivedString = str;
}
}
class HandlerObject
{
public void HandlerMethod1(string s)
{
//magic
}
public void HandlerMethod2(string s)
{
//different kind of magic
}
}
class Program
{
static void HandlerMethod3(string s)
{
//another kind of magic!
}
static void Main(string[] args)
{
StrClass class1 = new StrClass();
StrClass class2 = new StrClass();
StrClass class3 = new StrClass();
HandlerObject handler = new HandlerObject();
class1.PropertyChanged += (s, e) => { handler.HandlerMethod1(s.ToString()); };
class2.PropertyChanged += (s, e) => { handler.HandlerMethod2(s.ToString()); };
class3.PropertyChanged += (s, e) => { HandlerMethod3(s.ToString()); };
}
}
I am trying to get a custom enum class working which should enable me to create enums with user friendly identifiers and an arbitrary associated value. so far so good:
public class EnumBase<T, E>
where E : class
{
private static readonly List<E> list = new List<E>();
private string text;
private T value;
public string Text { get { return text; } }
public T Value { get { return value; } }
public EnumBase(string text, T value)
{
this.text = text;
this.value = value;
list.Add(this as E);
}
protected static IEnumerable<E> ItemList
{
get { return list; }
}
}
public class Zahlungsart : EnumBase<int, Zahlungsart>
{
public static readonly Zahlungsart Erlagsschein = new Zahlungsart("Erlagsschein", 0);
public static readonly Zahlungsart Lastschrift = new Zahlungsart("Lastschrift", 1);
private Zahlungsart(string text, int value) : base(text, value) { }
public static new IEnumerable<Zahlungsart> ItemList { get { return EnumBase<int, Zahlungsart>.ItemList; } }
}
And now my problem:
Console.WriteLine(Zahlungsart.ItemList.Count());
The following statement gives me 0, instead of 2. The problem is due to beforefieldinit, I think. I could work around this by calling some method of the specific enum directly which would force the static fields to load, but this is not the best solution, I think.
Hint: please do not propose some kind of [UserfriendlyName()]-attribute for enum here, I already know them.
EDIT
Thanks, hans. I had indeed a typo in my own code, calling the wrong generic specialisation.
Now my question is, can I get rid of the redefinition of ItemList in each subclass, but it seems this is necessary to to get the static fields initialized.
How about using "static constructor" ??
public class Zahlungsart : EnumBase<int, Zahlungsart>
{
public static readonly Zahlungsart Erlagsschein;
public static readonly Zahlungsart Lastschrift;
static Zahlungsart()
{
Erlagsschein = new Zahlungsart("Erlagsschein", 0);
Lastschrift = new Zahlungsart("Lastschrift", 1);
}
private Zahlungsart(string text, int value) : base(text, value) { }
public static new IEnumerable<Zahlungsart> ItemList { get { return EnumBase<int, Zahlungsart>.ItemList; } }
}
Your code doesn't repro the problem. But you will get a repro if you change the property like this:
public new static IEnumerable<Zahlungsart> ItemList {
get { return EnumBase<uint, Zahlungsart>.ItemList; } // Note: uint instead of int
}
Beware that every concrete class generated from a generic type will have its own static fields, they are not shared.