Ok, first, excuse my english. Well, I stay making a SAVEFILE with [Serializable()], there's not the problem, the problem is, when I try to make a change of a this static string with the Username, I can't find the reference to this variable in the other script with de InputField. Nothing strange, the SAVEFILE script just say:
and the script save:
public static UIsettings uisettings;
//Data to save.
public string AirlineName = "Unknow";
public string UserName = "Unknow";
//Autoload.
public bool StartupLoad;
void Awake()
{
if(uisettings == null)
{
uisettings = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
void Start()
{
if (StartupLoad)
{
Load();
}
}
//Guardar
public void Save() //Start the SAVEGAME code
later, I change the value of Airline Name and Username from other two scripts in InputFields, the two methods look like these:
public void SubmitName(string newAirlineName)
{
if(newAirlineName == "")
{
print("Write a valid name");
}
else
{
print(newAirlineName + " es valido.");
profileData.AirlineName = newAirlineName;
profileData.Save();
Debug.Log(UIsettings.uisettings.AirlineName);
}
}
If I call it like this, work, but is useless bacause when I change of scene these values go again to Default, so I use static in the values like:
{
public static string AirlineName = "Unknow";
}
without keys, obiously. But, when I make this the metod of the second script can't show the assigned variable, say: error CS0176: Member 'UIsettings.AirlineName' cannot be accessed with an instance reference; qualify it with a type name instead...
I have a few days trying to solve this by myself but, I dunno what to do.
Is to know that the SAVEGAME script is a DontDestoyOnLoad file, like can be see in the first script, but I this that this is't 'cause the script works fine without the static.
When you have a static variable (public static string AirlineName) you can only reference it using the class name -- not an instance of the class - because only one AirlineName exists, and it is not related to any instance of your class.
Here's an example of why you're getting your error:
// This example shows why are you getting the error. Skip to the second example
// to see the solution that you should use
public class UiSettings : MonoBehaviour
{
public static string AirlineName = "Unknow";
}
// ...
public void SubmitName(string newAirlineName)
{
// Just an example of getting the current instance of UiSettings
UiSettings profileData = (UiSettings)GameObject.FindObjectOfType(typeof(UiSettings));
// You can't do this because AirlineName is a static property, so you can't use an
// instance variable (profileData) to access it because AirlineName doesn't belong
// to an instance
profileData.AirlineName = newAirlineName;
// You would have to access it like this
UiSettings.AirlineName = newAirlineName;
}
But since you're making UiSettings a singleton class by using DontDestroyOnLoad, you would do this
public class UiSettings : MonoBehaviour
{
public static UIsettings uisettings;
// Do not make these static
public string AirlineName = "Unknow";
public string UserName = "Unknow";
void Awake()
{
if(uisettings == null)
{
uisettings = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
}
// ...
public void SubmitName(string newAirlineName)
{
// uisettings contains an instance of UiSettings, so you are allowed to say
// UiSettings.uisettings.AirlineName = ...
UiSettings.uisettings.AirlineName = newAirlineName;
}
I would also recommend changing the name uisettings to Instance to make it clear that the property references the singleton instance of the class. Like this:
public class UiSettings : MonoBehaviour
{
// Instead of public static UiSettings uisettings
public static UiSettings Instance { get; private set; }
}
Related
I would like to pass values from one class file to another class.
E.g:
Step1:
Class1.cs
public class Class1
{
public string LogedInPerson { get; set; }
public string Name
{
get { return this.LogedInPerson; }
set { this.LogedInPerson = value; }
}
}
Step2:
Value has been assigned in below method:
test.xaml.cs
public void assignValue()
{
Class1 obj = new Class1();
obj.LogedInPerson = "test123";
}
Step3:
I would like to get "test123" values from Class2.cs.
E.g:
public void test()
{
string selected_dept = ?? //How to get "test123" from here.
}
You can have variables class that includes public variables. Define instance of class1 in variables class .
public static class1 myclass=new class1();
in test.xml.cs set value
public void assignValue()
{
myclass.LogedInPerson = "test123";
}
in class2.cs
public void test()
{
string selected_dept = myclass.LogedInPerson;
}
Initialize Class1 outside assignValue() methos
Class1 obj = new Class1();
public void assignValue()
{
obj.LogedInPerson = "test123";
}
public string returnValue()
{
return obj.LogedInPerson;
}
if your second class name test.xaml then call it like this, but I don't think you can use class name test.xaml so use a nice name instead there eg: Class2
public void test()
{
test.xaml test = new test.xaml();
test.assignValue();
string selected_dept = test.returnValue(); //How to get "test123" from here.
}
I believe this question is more on the topic of basic Object Oriented Programming principles, not so much about WPF specific features. Therefore, I will provide you a non-WPF specific answer, as it will allow me to address your question in the most direct way.
In OOP, a method can return a result to the caller. So, for instance,
public string GetReturnObject(){
return "This is a return object";
}
You can create a new object and pass it back to the caller,
public void Test(){
string data = GetReturnObject();
}
And now data will be assigned the object that was returned from the method that Test() called. So, if you modify your AssignValue method by adding a return type and passing the instantiated Class1 object back to the caller, you will have the answer you need
public Class1 assignValue()
{
Class1 obj = new Class1();
obj.LogedInPerson = "test123";
return obj;
}
Hope that helps.
I've declared a list in a class. I want to access the list from another class. How can I access the list from a module of another class?
// ClsUser.cs
namespace WebLll.ApiPayment.BusinessObject
{
public class ClsUser
{
Data.MyEntity db = new Data.MyEntity("MyEntity1");
public List<Data.GetPaymentRslt> BRIlstTxn = db.GetPayment(obj.PaymentCode, dtFrom, dtTo, obj.PaymentMode).ToList();
//... remaining code
}
}
// clsWebLllAPI.cs
namespace WebLll.ApiPayment.BusinessObject
{
public class clsWebLllAPI : clsBaseApi
{
public void Initialize(api_rule_setup obj)
{
// access the BRIlstTxn here
}
}
}
Since the list is public you can simply create an instance of the class and access it like follow,
ClsUser clsuser=new ClsUser();
List<Data.GetPaymentRslt> mylist=clsuser.BRIlstTxn; // Simply access PUBLIC field
From MSDN
Accessing a field in an object is done by adding a period after the object name
But as good programming practice,I suggest you to use Accessors over making a field public (need to know why, check this)
Suggestion code :
// ClsUser.cs
namespace WebLll.ApiPayment.BusinessObject
{
public class ClsUser
{
Data.MyEntity db = new Data.MyEntity("MyEntity1");
private List<Data.GetPaymentRslt> BRIlstTxn = db.GetPayment(obj.PaymentCode, dtFrom, dtTo, obj.PaymentMode).ToList();
// Only GET . Provide protection over setting it
public List<Data.GetPaymentRslt> brIlstTxn{
get
{
return BRIlstTxn;
}
}
//... remaining code
}
}
// clsWebLllAPI.cs
namespace WebLll.ApiPayment.BusinessObject
{
public class clsWebLllAPI : clsBaseApi
{
public void Initialize(api_rule_setup obj)
{
ClsUser clsuser=new ClsUser();
List<Data.GetPaymentRslt> mylist=clsuser.brIlstTxn; // Now you are accessing GET accesor rather than field directly
}
}
}
You can use Dot, member access operator to access public/internal/protected data member (list) of other class.
namespace WebLll.ApiPayment.BusinessObject
{
public class clsWebLllAPI : clsBaseApi
{
public void Initialize(api_rule_setup obj)
{
ClsUser clsUser = new ClsUser ();
var lst = clsUser.BRIlstTxn;
}
}
}
Say I have a class declared as follows:
public class ExampleClass
{
public Action<int> Do { get; set; }
public ExampleClass()
{
}
public void FuncA(int n)
{
//irrelevant code here
}
public void FuncB(int n)
{
//other irrelevant code here
}
}
I want to be able to use this class like this
ExampleClass excl = new ExampleClass() { Do = FuncA }
or
ExampleClass excl = new ExampleClass() { Do = excl.FuncA }
or
ExampleClass excl = new ExampleClass() { Do = ExampleClass.FuncA }
I can compile the second option there, but I get a "Delegate to an instance method cannot have null 'this'." exception when I hit that code. The third one doesn't even make sense, because FuncA isn't static.
In my actual code, there will be maybe 10-15 different functions it could get tied to, and I could be adding or removing them at any time, so I don't want to have to have a large switch or it-else statement. Additionally, being able assign a value to 'Do' when instantiating the class is very convenient.
Am I just using incorrect syntax? Is there a better way to create a class and assign an action in one line? Should I just man up and manage a huge switch statement?
You have to create the instance of the class and later set the property to the instance member. Something like:
ExampleClass excl = new ExampleClass();
excl.Do = excl.FuncA;
For your line:
ExampleClass excl = new ExampleClass() { Do = FuncA }
FuncA is not visible without an instance of the class.
For:
ExampleClass excl = new ExampleClass() { Do = excl.FuncA }
Instance has not yet been created that is why you are getting the exception for null reference.
For:
ExampleClass excl = new ExampleClass() { Do = ExampleClass.FuncA }
FuncA is not a static method, you can't access it with the class name.
In object initializer syntax you cannot access the variable being initialized before it is definitely assigned:
ExampleClass excl = new ExampleClass()
{
Do = excl.FuncA //excl is unavailable here
}
Read Object and Collection Initializers (C# Programming Guide) for more info.
You could do the following, for example:
public class ExampleClass
{
public Action<int> Do { get; set; }
public ExampleClass(bool useA)
{
if (useA)
Do = FuncA;
else
Do = FuncB;
}
public void FuncA(int n)
{
//irrelevant code here
}
public void FuncB(int n)
{
//other irrelevant code here
}
}
and use it:
ExampleClass exclA = new ExampleClass(true);
ExampleClass exclB = new ExampleClass(false);
Another idea is if these functions may be declared as static (i.e. they don't need any instance members of the ExampleClass), then this would work:
public class ExampleClass
{
public Action<int> Do { get; set; }
public ExampleClass() { }
public static void FuncA(int n) { /*...*/}
public static void FuncB(int n) { /*...*/}
}
and use it the way you want:
ExampleClass excl = new ExampleClass() { Do = ExampleClass.FuncA };
If you have extension methods make sure that those values are not null before invoking the extension methods or handle nulls inside the extension methods.
For example
public static ExtensionClass
{
public static bool RunExtensionMethod(this object myObject)
{
var someExecutionOnMyObject = myObject.IsValid();
//the above line would invoke the exception when myObject is null
return someExecutionOnMyObject ;
}
}
public void CallingMethod()
{
var myObject = getMyObject();
if(myObject.RunExtensionMethod()) //This would cause "delete to an instance method cannot have null" if myObject is null
{
}
}
To handle this scenario handle nulls and assert nulls if you own the extension class.
public static ExtensionClass
{
public static bool RunExtensionMethod(this object myObject)
{
if(myObject == null) throw new ArgumentNullException(nameof(myObject));
var someExecutionOnMyObject = myObject.IsValid();
return someExecutionOnMyObject ;
}
}
public void CallingMethod()
{
var myObject = getMyObject();
if(myObject != null && myObject.RunExtensionMethod())
{
}
}
i've been wondering why my variable is not saving data. this is my code
class MainProg
{
public string name;
static void Main()
{
MainProg m = new MainProg();
m.Start();
}
public void Start()
{
Register rs = new Register();
Register r = (Register)rs;
r.run();
Console.WriteLine(name);
}
}
class Register : MainProg
{
public void run()
{
name = "a";
}
}
Did I forget anything?everytime I try to show the output it shows nothing.Thanks by the way for taking your time.
This will work.
class MainProg
{
static void Main()
{
Register rs = new Register();
Register r = (Register)rs;
r.run();
Console.WriteLine(r.name);
}
}
class Register : MainProg
{
public string name;
public void run()
{
name = "a";
}
}
The reason your code fails is that you are creating an instance of Register, which is separate from MainProg even though it inherits from it. You set the variable in the new instance, and then read it from the old.
name is an instance field so you need reference of an object.
Try,
Console.WriteLine(r.name);
Because you are changing the name inside the instance of Register called r then you print the var name inside the instance of MainProg.
To prove it try:
Console.WriteLine(r.name);
Since you are trying to access a member variable inside a static function it will throw an compilation error.
Try to access the variable using object like
Console.WriteLine(r.name);
The problem is that you are trying to write the name from this object. The variable you changed is located in the other object 'r'.
I have a class that requests that when called a string is sent when requesting / initializing it.
class Checks
{
public Checks(string hostname2)
{
// logic here when class loads
}
public void Testing()
{
MessageBox.Show(hostname2);
}
}
How would it be possible to take the string "hostname2") in the class constructor and allow this string to be called anywhere in the "Checks" class?
E.g. I call Checks(hostname2) from the Form1 class, now when the Checks class is initialized I can then use the hostname2 string in my Checks class as well
Declare a member inside the class and assign the value you passed to the member inside the constructor:
class Checks
{
private string hostname2;
public Checks(string hostname2)
{
this.hostname2 = hostname2; // assign to member
}
public void Testing()
{
MessageBox.Show(hostname2);
}
}
If you also need to have outside access, make it a property:
class Checks
{
public string Hostname2 { get; set; }
public Checks(string hostname2)
{
this.Hostname2 = hostname2; // assign to property
}
public void Testing()
{
MessageBox.Show(Hostname2);
}
}
Properties start with a capital letter by convention. Now you can access it like this:
Checks c = new Checks("hello");
string h = c.Hostname2; // h = "hello"
Thanks to Andy for pointing this out: if you want the property to be read-only, make the setter private:
public string Hostname2 { get; private set; }
You need to copy the constructor argument in a class variable:
class Checks {
// this string, declared in the class body but outside
// methods, is a class variable, and can be accessed by
// any class method.
string _hostname2;
public Checks(string hostname2) {
_hostname2 = hostname2;
}
public void Testing() {
MessageBox.Show(_hostname2);
}
}
You can expose a public property to retun the hostname2 value which is the standard for exposing your private varibles
class Checks
{
private string _hostname;
public Checks(string hostname2)
{
_hostname = hostname2;
}
public string Hostname
{
get { return _hostname; }
}
}