I have a base class like this:
public class Marker {
public int[] GetChildMarks() {
//Somehow Get Child int members
}
public int ShallNotBeInArray;
}
public class MyMarker : Marker {
public int Size, Number;
}
public class TedsMarker : Marker {
public int Power;
}
//... somewhere in main
var m = new MyMarker(){Size=3, Number = 666};
var arr = m.GetChildMarks(); // [Size, Number, Any other ints in MyMarker ]
var t = new TedsMarker() {Power=999};
var arr2 = t.GetChildMarks(); // [Power, Any other ints in TedsMarker]
So is it possible and how one can do such a thing in C# using reflection?
It can be achieved like this:
public class Marker
{
public int[] GetChildMarks()
{
return new int[]
{
(int)GetType().GetField("Size").GetValue(this),
(int)GetType().GetField("Number").GetValue(this)
};
}
public int ShallNotBeInArray;
}
This assumes that the child class has these two fields and they are of type int.
Since there is no enforcement (and actually there can't be because these are fields, not properties), this approach is a good candidate to produce runtime errors.
EDIT:
The values of all the fields can be retrieved like this:
public class Marker
{
public int[] GetChildMarks()
{
List<int> allIntegerFields = new List<int>();
// DeclaredOnly: only get fields declared by this type, not the ones declared by base classes
// Public | Instance: Only get non-static, public fields
foreach(FieldInfo fieldInfo in GetType().GetFields(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance))
{
if(fieldInfo.FieldType == typeof(int))
{
allIntegerFields.Add((int)fieldInfo.GetValue(this));
}
}
return allIntegerFields.ToArray();
}
public int ShallNotBeInArray;
}
Related
I want this method to work with any variable - i.e., passing a "Price" value to the method then getting the total price of all items.
private int GetTotalValue(int stat){
int total = 0;
foreach(Item i in Vendor.items){
totalStat += i.stat;
}
return total;
}
However, it has no way of knowing the name of the variable that I passed as the parameter, and thus no way of accessing it in other objects.
How would I tell the method what variable I'm passing, instead of just the value of it?
If you always want the sum of some property value you could encapsulate that logic into a method, e.g. GetVendorItemSum:
internal class Program
{
private static void Main(string[] args)
{
var items = new[] {
new Item {Price = 1},
new Item {Price = 2}
};
var vendor = new Vendor {Items = items};
var vendorSum = GetVendorItemsSum(vendor, x => x.Price);
}
private static int GetVendorItemsSum(Vendor vendor, Func<Item, int> func)
{
return vendor.Items.Sum(func);
}
}
public class Vendor
{
public IEnumerable<Item> Items;
}
public class Item
{
public int Price { get; set; }
}
I have this assignment:
Counts.btnCountViewsAvg.BtnCount = 123;
Here are the classes that I use:
public static class Counts
{
public static BtnCountViews btnCountViewsAvg;
}
public class BtnCountViews // this class used in many places
{
public int BtnCount { get; set; }
public int Views { get; set; }
}
What I would like to do is to assign 123 to BtnCount but it says cannot assign to a null. When I check the btnCountViewsAvg is null. I used static as I only want to have one Counts class in the application.
Can someone give me some advice on how I can assign a value to Counts.btnCountViewsAvg.BtnCount
It is your Counts.btnCountViewsAvg that is null. You need to instantiate that before being able to set the BtnCount property.
To instantiate the value you need to do the following:
Counts.btnCountViewsAvg = new BtwCountViews();
Furthermore you could instantiate using the object initialiser it like so:
Counts.btnCountViewsAvg = new BtwCountViews { BtnCount = 123 };
In order to ensure that btnCountViewsAvg is only created once you could do the following:
public static class Counts
{
public readonly static BtnCountViews btnCountViewsAvg = new BtnCountViews();
}
Or to follow on from Jon Skeets suggestion with using a property rather than a public field this would be a better approach:
public static class Counts
{
public static ButtonCountViews ButtonCountViewsAvg { get; } = new ButtonCountViews();
}
Note I renamed your class to remove the abbreviation.
You have two options:
Create new object only once
public static class Counts
{
public static BtnCountViews btnCountViewsAvg = new BtnCountViews();
}
Or create it every time you need it:
Counts.btnCountViewsAvg = new BtnCountViews()
{
BtnCount = 123
};
You, probably, want something like this: create an instance of BtnCountViews with BtnCount = 123 and assign it to static field:
public static class Counts
{
// we create a instance: new btnCountViewsAvg()
// then we set up a property of this instance: { BtnCount = 123, }
public static BtnCountViews btnCountViewsAvg = new btnCountViewsAvg() {
BtnCount = 123,
};
}
I want to add row number in object list.
here's the they i do it now but there must be better way
Profile for mapping
public class VendorEnquiryDM_TO_VM : Profile
{
public VendorEnquiryDM_TO_VM()
{
CreateMap<VENDORENQUIRY, VendorEnquiryVM>();
}
}
public class VendorEnquiryVM_TO_DM : Profile
{
public VendorEnquiryVM_TO_DM()
{
CreateMap<VENDOR_ENQUIRY, VendorEnquiryVM>().ReverseMap();
}
}
Register profile
cfg.AddProfile<VendorEnquiryDM_TO_VM>();
cfg.AddProfile<VendorEnquiryVM_TO_DM>();
This is how I add sno.
alldata = Mapper.Map<IEnumerable<Vendor_EnquiryVM>>(objDAO.getVendorEnquiry());
var _roles = alldata.Select((t, index) => new Vendor_EnquiryVM
{
sno = index + 1,
CONTACT_NO=t.CONTACT_NO,
DATE=t.DATE,
EMAIL=t.EMAIL,
id=t.id,
FIRST_NAME=t.FIRST_NAME,
wer=t.wer,
asdf=t.asdf
});
Due to just one serial no. I need to assign all properties and this is somewhat fraustrating to me for large model, please suggest me better way of doing this.
You can define a static Id and when you create the class, increment it by one
here how your class code should look like
public class Test
{
private static int mId = 0;
public Test()
{
mId = mId +1;
}
public int Id
{
get{ return mId;}
}
}
Here a demo
in order to use the same idea with collections like List, I applied some modifications and here what you can do
public class Test
{
private static int mIndex = 0; // this parameter will be incremented for each new Test
private int mId =0; // this parameter will hold the last incremented value
public Test()
{
mId = ++mIndex; // mIndex++ if you want to start with 0
}
public int Id
{
get{ return mId;}
}
}
Demo with lists
hope this will help you
I'm developing a class which contains some const strings
public static class Constants
{
public const string CarID= "car_id";
//public const string NumberID= "number_id"; // this is the second const string might be added, so
//the new created function can return the two
}
public class CarENParameters
{
public string Params { get; set; }
public CarENParameters(string carId)
{
Params = carId;
}
}
public static class CarPropertyProcess
{
//test params
public static CarENProps Parse(Uri uri,string content)
{
string carID= Regex.Matches(content, #"\$\('#CarXL'\)\.val\((\d+)\)", RegexOptions.None)[0].Groups[1].Value;
var parameters = new Dictionary<string, string>
{
{Constants.CarID, carID},
};
return new CarENProps(uri.AbsoluteUri, parameters);
}
public static CarENParameters GetParameters()
{
return new CarENParameters(Constants.CarID);
}
}
In the class Constants, I have one carID, now the case is it might have more than one const string like : public const string NumberID= "number_id";
So I want to create one function to return a list of those const strings, which are car_id and number_id with a class name CarENParameters but I havent figured out how to return a list by a get/set in a class, should I use dictionary or keyvaluespair to achieve that ? I'm quite new to C# so hope that I can have a better point of view from the helps of you guys. Thanks
Are you looking for something like this:
public static List<CarENParameters> GetParameters()
{
return new List<CarENParameters>()
{
new CarENParameters(Constants.CarID1),
new CarENParameters(Constants.CarID2),
new CarENParameters(Constants.CarID3)
}
}
You can use reflection for this
don't forget to put using System.Reflection;
// get class type
Type type = typeof(Constants);
// get a list of fields
FieldInfo[] fields = type.GetFields();
List<CarENParameters> list = new List<CarENParameters>();
// loop on field list
foreach (FieldInfo field in fields)
{
// if field is a string add it to our return list
if (field.FieldType == typeof(String))
list.Add(new CarENParameters((String) field.GetValue(null)));
}
I would like an advice. My project have a lot of equals methods with different values, and i would like to do a single method that does the same.
The methods are this:
private void Enum1()
{
Console.WriteLine(Enum.GetValue(ENUM1.Code));
Console.WriteLine(Enum.GetValue(ENUM1.Info));
}
private void Enum2()
{
Console.WriteLine(Enum.GetValue(ENUM2.Code));
Console.WriteLine(Enum.GetValue(ENUM2.Info));
}
private void Enum3()
{
Console.WriteLine(Enum.GetValue(ENUM3.Code));
Console.WriteLine(Enum.GetValue(ENUM3.Info));
}
This is the enums:
public enum ENUM1
{
Code = 1,
Info = 3
}
public enum ENUM2
{
Code = 91,
Info = 4
}
public enum ENUM3
{
Code = 6,
Info = 27
}
There is only a way to create a method by inserting the input type of enum to use? maybe a similar solution of this:
private void General("ENUM1")
{
var type = ENUM1;
switch (p)
{
case "ENUM1":
type = ENUM1;
case "ENUM2":
type = ENUM2;
case "CASALINGHI":
type = ENUM3;
default:
type = ENUM1;
}
Console.WriteLine(Enum.GetValue(type.Code));
Console.WriteLine(Enum.GetValue(type.Info));
}
I think something like this is what you are looking for:
private void General<T>()
{
var values = Enum.GetValues(typeof(T));
foreach(var value in values)
Console.WriteLine(value);
}
General<Enum1>();
General<Enum2>();
General<Enum3>();
Or this, depending on how you want to use it:
private void General(Type enumType)
{
var values = Enum.GetValues(enumType);
foreach(var value in values)
Console.WriteLine(value);
}
General(typeof(Enum1));
General(typeof(Enum2));
General(typeof(Enum3));
Why do you keep using enums, when you can easily use classes? Read more about Object-Oriented programming.
Create a single class:
public class MyEnum
{
public int Code
{
get; set;
}
public int Info
{
get; set;
}
public string Display()
{
Console.WriteLine(this.Code);
Console.WriteLine(this.Info)
}
//
// This will keep your enums static, available from any method
//
private static List<MyEnum> _globals = new List<MyEnum();
public static List<MyEnum> Globals ()
{
if (this._globals.Count == 0)
{
this._globals.Add(new MyEnum(){ Code = 1, Info = 3 });
this._globals.Add(new MyEnum(){ Code = 91, Info = 4 });
this._globals.Add(new MyEnum(){ Code = 6, Info = 27 });
}
return this._globals;
}
}
After this you can easily print out all the enums with the following code:
foreach (MyEnum* en in MyEnum.Globals())
{
en.Display();
}
Please look into solutions similar to this one, since your enum's obviously represent some data.