I'm calling getName() method from Achiv class on an ArrayList in printAchiv() method located in Achievements script and it throws an error.
Here is the error message that I get on the line Debug.Log("Achiv "+i+": "+ achivList[i].getName());:
Type object' does not contain a definition for getName' and no
extension method getName' of type object' could be found (are you
missing a using directive or an assembly reference?)
I'm just trying to access value of var "name" from obejct in collection.
Achiv class :
using UnityEngine;
using System.Collections;
public class Achiv: MonoBehaviour
{
public string name;
public Achiv(string name)
{
this.name = name;
}
public string getName()
{
return name;
}
}
Achievements script :
using UnityEngine;
using System.Collections;
public class Achievements: MonoBehaviour
{
public ArrayList achivList = new ArrayList();
void Start()
{
achivList.Add(
new Achiv("First name", "Descirptionn", false));
achivList.Add(
new Achiv("Second name", "Descirptionnn", false));
printAchiv();
}
void printAchiv()
{
for (int i = 0; i <= achivList.Count - 1; i++)
Debug.Log("Achiv " + i + ": " + achivList[i].getName());
}
}
Use List<Achiv> instead of ArrayList. ArrayList is archaic, not type safe shouldn't be used anymore.
Indexer of ArrayList returns object that's why you get the error. Try the following.
public List<Achiv> achivList = new List<Achiv>();
Apart from this,
Don't expose List publicly, prefer ReadOnlyCollection or IEnumerable.
Prefer foreach over for unless there is a good reason.
printAchiv doesn't follow proper naming convention, In c# we use "CamelCase", Rename it to PrintAchiv.
get/set methods are for java style languages which doesn't supports properties. In c# we use properties instead. Create a property namely Name.
The problem is that the elements inside the ArrayList are stored as object. Thus achivList[i] returns an object, which does not provide the getName() method.
Either you can add a cast:
Debug.Log("Achiv "+i+": "+ (Achiv)achivList[i].getName());
or you can switch to a generic List:
using UnityEngine;
using System.Collections.Generic;
public class Achievements: MonoBehaviour {
public List<Achiv> achivList = new List<Achiv>();
void Start () {
achivList.Add (new Achiv("First name", "Descirptionn", false));
achivList.Add (new Achiv("Second name", "Descirptionnn", false));
printAchiv();
}
void printAchiv(){
for (int i = 0; i <= achivList.Count - 1; i++)
{
Debug.Log("Achiv "+i+": "+ achivList[i].getName());
}
}
}
ArrayList operates with Objects. You need to cast result of array indexing to Achiv:
(achivList[i] as Achiv).getName()
Related
I am new to coding and I have a problem with using ToString override. When I try to use already overloaded class's ToString in other ToString override, I get this error:
An object reference is required to non static field, method, or property Freight.ToString()
Please help!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TruckCmopany
{
class Truck
{
private string name;
private double weightCapacity;
private List<Freight> freights;
public Truck(string name,double weightCapacity)
{
this.Name = name;
this.WeightCapacity = weightCapacity;
List<Freight> freights = new List<Freight>();
}
public string Name
{
get { return name; }
set { name = value; }
}
public double WeightCapacity
{
get { return weightCapacity; }
set { weightCapacity = value; }
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append(this.Name).Append(" - ");
if (freights.Count==0)
{
sb.Append("Nothing loaded");
}
else
{
sb.Append(string.Join(", ", freights)).Append(Freight.ToString());
}
return sb.ToString();
}
public IReadOnlyCollection<Freight> Freights
{
get => freights.AsReadOnly();
}
public void AddFreight(Freight freight)
{
}
}
}
Freight.ToString() is a call to a static method. It confuses the compiler, because it tries to resolve the call to the non-static .ToString inherited from object.
Since static classes cannot override members, if you really need a static ToString in your Freight class, you need to mark the method with new public.
Well, I see that your Freight is not a static class.
Then if I got you right, and you want a comma-separated string of freights, you need to simply do
sb.Append(string.Join(", ", freights));
It will call .ToString for each element implicitly.
To be able to call Freight.ToString() ToString() has to be a static function, i.e., a function that belongs to the class itself that doesn't require any specific instance of the class to get invoked. However when you convert ToString to be static, you won't have access to the this modifier, since in a static method, there is no instance that you can refer to with this. So you are going to have to pass an instance of Freight to your static function.
You can then override ToString() and inside pass this to your static function. If you want to.
Read on Static Members: MSDN
Read on Methods: MSDN
I can't find this addressed on SO. I am porting a Windows .NET application, that compiles and runs perfectly, to Mono on Linux. I have missed something small. Here is a part of the code:
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace DAPTimeClock
{
public static class DatabaseOps
{
private static string _dbFile;
public static string Get_dbFile()
{
return _dbFile;
}
public void Set_dbFile(string value)
{
this._dbFile = value;
}
public static bool foundFile = false;
public static string SetFile(String dblocation = #"Data" +
"Source=../db/TimeClock.db; Version=3;")
{
Set_dbFile( dblocation );
int pathStart = Get_dbFile().IndexOf ('=') + 1;
int pathEnd = Get_dbFile().IndexOf (";") - 1;
string filePath = Get_dbFile().Substring (pathStart,
pathEnd - pathStart + 1);
if (File.Exists (filePath)) {
foundFile = true;
return string.Format ("The db file {0} has been " +
"located", filePath);
} else
{
foundFile = false;
return string.Format("Unable to find db file {0}.",
filePath);
}
}
public static bool AddPerson(Person p)
{
bool result = false;
Class Continues .....
Here are the issues:
Other classes can't find any methods from this class. ex. DatabaseOp.Set_dbFile() Yields no such method.
The methods in this class can't find methods from this class.
The methods in this class can't see the outside classes.
If I pass an argument to the methods in the class, the complier says it can't find a parameter by that name.
The methods in the class can't see its own member variables.
I have done the following:
I removed the static, now making regular objects. (no change)
I double checked the namespaces. (all the same, no typos)
I tried making the member variable public and adding a get; and set;
I am stumped. Can anyone see what might be hanging this up? Is there something about mono I missed? All other classes are working fine.
Set_dbFile should be declared as
public static void Set_dbFile(string value)
compiler should complain: "cannot declare instance members in static class". Have you miss this?
I have developed the following class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ESROWCFData
{
public class ESROWFCData
{
public string GetNCAMSData()
{
//int iOffset = 0, iTake = 0;
string strOffset = "iOffset", strTake = "iTake";
string strNCAMS = "SELECT * FROM[HRO_REPORTS].[dbo].NCAMS WHERE DATEPART(YEAR, VisitStartDate) = DATEPART(YEAR, GetDate()) ORDER BY VisitorID OFFSET " + strOffset + " rows fetch next " + strTake + " rows only";
return strNCAMS;
}
}
}
and have included the using ESROWCFData; statement in my main program but when I try to call the GetNCAMSData() function it does not show up and I get the error that it does not exist. I am obviously doing something wrong but I cannot see what it is.
You have two options here. You can either make the method static so you can call it without creating an instance of your class by changing the signature to be:
public static string GetNCAMSData()
Then call it like this:
var result = ESROWFCData.GetNCAMSData()
Or you could create a new instance of the class and then call it off that like follows
var instance = new ESROWFCData();
var result = instance.GetNCAMSData()
You first have to create an instance of the ESROWFCData class:
ESROWFCData data = new ESROWFCData();
and then use it:
string s = data.GetNCAMSData();
First of all your namespace and class name are the same :
namespace ESROWCFData
{
public class ESROWFCData
{
...
So even if you want to use this class outside you have to use full type name :
ESROWCFData.ESROWCFData data = new ESROWCFData.ESROWCFData();
In case you're trying to use it like such :
ESROWCFData data = new ESROWCFData();
Compiler then is confused because of that namespace name.
Consider name changes on the namespace or class to resolve that issue.
More about that issue
Another issue is ( the one we do not know much about ) how are you trying to call that object's method. If you want to just use them statically, mark it as static :
namespace ESROWCFData
{
public class ESROWCFData
{
public static string GetNCAMSData()
{
...
And you can call them like so : ESWROWCFData.ESWROWCFData.GetNCAMSData()
I have to take this to a program that can handle a Double linked list, but I am very new to C# and windows forms. I have the following code so far.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace doublelinkedtest
{
public class nodetoDBList
{
public object elements;
public nodetoDBList prev;
public nodetoDBList next;
public nodetoDBList (int temp)
{
elements = temp;
next = null;
}
public void inserToList(object elements)
{
nodetoDBList newLink;
newLink = new nodetoDBList (elements);
}
}
}
But now I get the following error:
Argument 1: Cannot convert from 'object' to 'int'.
Why do I get this error?. I am only referencing the variable, I am not converting it.
I am very new to C#. And as you can see I am taking this project step by step in order to achieve a double linked list project. Please Help!.
You're calling the nodeToDBList constructor (which takes an int) with an object instead:
public nodetoDBList (int temp) <- Constructor takes an int
{
elements = temp;
next = null;
}
public void inserToList(object elements)
{
nodetoDBList newLink;
newLink = new nodetoDBList (elements); <- passing in an object instead
}
Since elements is declared as an object, and it's an object in the insertToList method, odds are you should modify the constructor so that temp is an object instead of an int.
In my source code for a C# class, I want to use the values of parameters defined within some other class. I want to do it without "hardwiring" the other class name into the source code (e.g., without writing something like "class2.variable").
Rather, I want to pass the name of that other class as a character string at runtime.
I am using C# within Unity. So I want to set the name of the other class as a public string within the Inspector of Unity.
For example, consider these two separate scripts:
using UnityEngine ;
public class ScriptA : ScriptableObject {public static int fred = 5 ; }
and
using System;
using System.Reflection;
using UnityEngine;
public class ScriptB : MonoBehaviour {
object item;
private static string instance;
void Start() {
instance = "ScriptA";
item = ScriptableObject.CreateInstance(Type.GetType(instance));
Type myType = item.GetType();
foreach (FieldInfo info in myType.GetFields())
{
string infoName = info.Name; //gets the name of the field
Debug.Log (" info = " + infoName);
}
}
}
ScriptB works OK ; it accesses ScriptA just from the string "instance", as evidenced by the fact that
the name "fred" to appears in the console.
But how do I access the value of "fred" ; how do I make the number "5" appear on the console?
I have been trying for two days. I have searched extensively for an answer.
Can somebody please help?
FieldInfo has a GetValue method :
public abstract object GetValue(
object obj
)
Try:
Type myType = item.GetType();
foreach (FieldInfo info in myType.GetFields())
{
string infoName = info.Name; //gets the name of the property
Console.WriteLine(" Field Name = " + infoName +"and value = "+ info.GetValue(null));
}