I am looking at a pattern implemented in Java and have some questions about how it aligns to (can be ported to) C#.
Java:
class Foo
{
private Class someClass;
...
}
class Bar
{
private Field some Field;
}
First, Class stores an instance of a domain object. It looks like Java exposes reflection methods on the type which are used to access fields on the object through reflection. What would type would be synonymous in C#? Would I use object and then use MethodInfo or is there a better way?
Second, Field is type in the framework and is assigned by using:
someClass.getDeclaredField(fieldName)
Is there a parallel in the .NET framework i should use?
Right now I created a custom object in place of the Class in Foo, and I created a custom object for Field. Is there a preferred way to do this?
You may take a look at the FieldInfo type and GetField method.
Code might look something among the lines:
class Foo
{
public Type someClass;
...
}
class Bar
{
private FieldInfo some_Field;
public Assign(string fieldName)
{
Foo foo = new Foo();
some_Field = foo.someClass.GetField(fieldName);
}
}
You may also get the value of the field by using:
foo.GetType().GetField("name").GetValue(foo).ToString()
In this example, we assume class foo has a field named "name". What does this help? Well think it as this way:
private string getValueOfUnknownField(string fieldName)
{
return(foo.GetType().GetField(fieldName).GetValue(foo).ToString());
}
Even if you change class foo and add new fields to it, you don't need to change getValueOfUnknownField method.
Related
So I got an assignment [college student] to create a program that runs a garage. I have a class for every car type [FuelMotorcycle, ElectricMotorcycle, FuelCar, ElectricCar, etc.], each car type has its own constructor and they all differ from one another.
One of the assignment requirements is to "place the code that creates car objects [new], and this code alone, in a class on the logical part of the program, this code part cannot turn to the user directly or indirectly" (translated).
So the way I see it, I have a class, let's say "EmptyCarCreator" , that will have methods such as:
public static FuelMotorcycle CreateNewFuelMotorcycle()
{
FuelMotorcycle EmptyFuelMotorcycle;
return EmptyFuelMotorcycle;
}
obviously this won't compile, and even if it did, I couldn't use the "FuelMotorcycle" class constructor after I get it returned.
I need the user to input the elements for the constructor.
So, is there any other way to do this? I feel like I am missing something very basic here.
Please excuse any English errors, hope my question was clear.
You would need something like this:
public static class EmptyCarCreator
{
public static T Create<T>() where T : class, new()
{
return new T();
}
}
Then you would use it like this:
FuelMotorcycle myVehicle = EmptyCarCreator.Create<FuelMotorcycle>();
This will create a new class through the parameterless constructor.
There are other options that might be able to handle parameters a little better like this:
public static class EmptyCarCreator
{
public static object Create(Type type)
{
return Activator.CreateInstance(type);
}
}
To use this you would have to cast this returned object.
FuelMotorcycle myVehicle = (FuelMotorcycle)EmptyCarCreator.Create(typeof(FuelMotorcycle));
Hello I'm using Visual Studio 2005 (because I need compact framework support) and my problem is with generics.
I have created an abstract class called AbstractDAO which is my base
From that I am creating other classes like DocumentDAO,HeaderDAO etc which represent different tables on my database
What I wish to do is retrieve a certain number of the above mentioned DAO classes, but as an AbstractDAO (the abstract class has a number of concrete implementations that I wish to use)
What I tried is
AbstractDAO<object> dao = new DocumentDAO();
AbstractDAO<object> dao = (AbstractDAO<object>)new DocumentDAO();
AbstractDAO<T> dao = new DocumentDAO();
I need the above because I have created a function that transfers data from one table to another similar table in a different database, so it would (if it worked) go something like this
AbstractDAO<object> dao_local = new DocumentDAO(local_database);
AbstractDAO<object> dao_remote = new DocumentDAO(remote_database);
do_transfer(dao_local,dao_remote)
void do_transfer(AbstractDAO<object> from, AbstractDAO<object> to) {
List<object> items = from.get_all();
to.insert(items);
}
Is there any way to do the above?
That will only work if your class hierachy is like this:
class DocumentDAO : AbstractDAO<object> {
//...
}
By your comment it seems like you have a type hierarchy like this:
class DocumentDAO : AbstractDAO<SomeType> {
public override SomeType Foo() {
//...
return someValue;
}
//...
}
class AbstractDAO<T> {
public abstract T Foo();
//...
}
You probably want to refactor AbstractDAO to implement a non generic interface like IAbstractDAO:
class IAbstractDAO {
object Foo();
//...
}
class AbstractDAO<T> {
public object Foo() {
return Foo();
}
public abstract T Foo();
//...
}
Any implementation of AbstractDAO<T> is compiled to a separate object type where T is replaced with the type. See "Is generics runtime or compile time polymorphism?" for more information on how this happens. In short, don't let the <T> fool you.
This means that you can't assign DocumentDAO to AbstractDAO<object> any more than you can assign String to it. Also a generic type is not the same as inheriting, which seems to be what you are trying to achieve.
In either case there are two standard solutions, as already mentioned.
The first is to operate on interfaces. You create an interface for the common properties and have AbstractDAO<T> or any other inherit from this. Then most of the time you simply operate on interfaces. Exactly how you organize it is up to you.
The second is to perform a shallow copy of the object. This means copying values and references from one object to the other. For this you usually use an object mapper like AutoMapper. This tutorial should get you started..
You can try to use Automapper to transfer your objects like this:
void do_transfer(AbstractDAO<FirstType> from, AbstractDAO<SecondType> to)
{
Mapper.Initialize(cfg=>cfg.CreateMap<FirstType, SecondType>);
List<FirstType> fromItems = from.get_all();
List<SecondType> itemsToInsert =
Mapper.Map<List<FirstType>, List<SecondType>>(fromItems);
to.insert(itemsToInsert);
}
By default automapper will map fields with same names. You can create configurations for complex type mapping.
So I finally found the answer to what I was trying to do, instead of assigning abstractDAO to something I created a factory that would retrieve the required AbstractDAO according to what type the generic was, and used this function
private bool transfer<T>(){
AbstractDAO<T> local = DAOFactory.get<T>(local_database);
AbstractDAO<T> remote = DAOFactory.get<T>(remote_database);
List<T> items = local.get_all();
foreach (T item in items) {
remote.insert(item);
}
}
That way I can call this function like this:
transfer< Document >();
transfer< Header >();
etc. and do a full transfer
edit: just for completeness' shake this is the factory I created
public static AbstractDAO<T> get<T>(Database database) {
Type t = typeof(T);
if (t == typeof(Document)) {
return new DocumentDAO(database) as AbstractDAO<T>;
} else if (t == typeof(Header)) {
return new HeaderDAO(database) as AbstractDAO<T>;
} etc.
}
With C#6 came some new features, including getter-only auto-properties and property-like function members.
I'm wondering what are the differences between these two properties? Is there any reason why I'd prefer one to another?
public class Foo
{
public string Bar {get;} = "Bar";
public string Bar2 => "Bar2";
}
I know that {get;} = can only be set by a static call or a constant value and that => can use instance members. But in my particular case, which one should I prefer and why?
It's easiest to show them in terms of C# 1:
public class Foo
{
private readonly string bar = "Bar";
public string Bar { get { return bar; } }
public string Bar2 { get { return "Bar2"; } }
}
As you can see, the first involves a field, the second doesn't. So you'd typically use the first with something where each object could have a different state, e.g. set in the constructor, but the second with something which is constant across all objects of this type, so doesn't need any per-object state (or where you're just delegating to other members, of course).
Basically, ask yourself which of the above pieces of code you would be writing if you didn't have C# 6 available, and choose the corresponding C# 6 path.
I've got a class A with a public field b
class A
{
public static string b;
}
but now I want to make b dynamic so I call it anything. So I can make the class a DynamicObject
class A : DynamicObject
{
}
but I the compiler doesn't let me now call A.dynamicThing cos I have to instantiate A as dynamic.
How can I mangle c# further to make this work?
I don't belive you're going to find a way to make this work. It's not just the DynamicObject that makes things work. The declaration as a variable of the "dynamic" data type is what tells the compiler to actually use the DynamicObject base to resolve the member access. With static access direct to the class, you don't have that. So I really just don't think this is going to work in C# unless that changes in the future.
It's not possible right now with .NET 4
more information in this article.
I think I understand now - the closest you can get is by using an ExpandoObject :
dynamic foo = new ExpandoObject();
foo.somethinghere = "bar";
foo.dynamicThing = "baz";
Edit:
I don't think its possible to re-route the access to a static property of a class
to an expando object if the name of the property does not match - how would the compiler know that that's what you meant to do? You are getting a compile time error after all, not a runtime error.
From MSDN:
When a field, method, property, event,
operator, or constructor declaration
includes a static modifier, it
declares a static member. In addition,
a constant or type declaration
implicitly declares a static member.
Static members have the following
characteristics:
When a static member M is referenced in a member-access (Section 7.5.4)
of the form E.M, E must denote a type containing M.
...
public class FakeDynamicMethodInvoker : DynamicObject
{
// your code here
}
public class FakeDynamicWrapper<T>
{
static FakeDynamicWrapper()
{
DynamicStaticField = (dynamic)new FakeDynamicMethodInvoker();
}
public static T DynamicStaticField{ get; set; }
}
public class RealClassWithDynamicStaticField: FakeDynamicWrapper<dynamic>
{
}
somewhere in a code:
RealClassWithDynamicStaticField.DynamicStaticField.AnyMethod();
C# doesn't let you really rename variables to some dynamic name at runtime. Your question is mangled.
If you are wanting variable b to have a dynamic object at runtime, then use the dynamic keyword.
Example:
dynamic b = GetBValue();
b.SomeOperation(); // the type of "b" will be evaluated/chosen at runtime.
Old question but worth to answer :)
Static constructors are the answer to these problems.
https://msdn.microsoft.com/en-us/library/k9x6w0hc.aspx
public class MyClass
{
public static dynamic StaticDynamicObject;
static MyClass()
{
StaticDynamicObject = new ExpandoObject();
StaticDynamicObject.Prop = "woohoo!";
}
}
Is it possible to create a "catchall" getter property in C#?
class xyzFactory {
public static object this.*(string name){
get { return new name();}
}
}
In PHP you would write something like
//static getters are new to 5.3, so I didn't put it here.
class xyzFactory{
public _get($name){ return $name();}
}
Not in C# 3. In C# 4.0 you could achieve something like this with expando properties and the dynamic keyword.
You can achieve this with a hack like
xyzFactory.Instance.Name
where static Instance property is of type dynamic
And make you xyzFactory derived from DynamicObject class.
public xyzFactory : DynamicObject
{
private static xyzFactory _instance = new xyzFactory();
private xyzFactory() { }
public static dynamic Instance
{
get{ return _instance; }
}
public override bool TryGetMember(GetMemberBinder binder, out object result) {
// ...
}
}
No, you can't do that in C#. C# is a compiled language and statically resolves method slots at compile time. It doesn't support passing the property name as string or things like that.
The closest you can get is overload index operator ([]). At least until C# 4.0 is out
You could use the property pattern to implement this, as others have said C# won't currently help you implement it though
You may be able to do this with LinFu. It uses a dynamic Proxy to allow for Duck Typing and Late Binding, Ruby-style Mixins