Other Classes in Class arguments - dart

How can I set another Class as a Class constructor argument?
class MyClass {
String message = 'myClass';
void print() {
print(this.message);
}
}
class TestClass {
var myClass;
TestClass(???) {
this.myClass = ???(); // ???
}
void debug() {
print('DEBUG: ');
this.myClass.print();
}
}
main() {
MyClass myClass;
testClass(myClass);
}

You can't (at least not now). Your best option is to pass a builder function into the constructor.
class MyClass {
var clazzBuilder;
MyClass(this.clazzBuilder);
doStuff() {
var instance = clazzBuilder();
:
}
}
and then use it like this
var myTest = new MyClass(() => new Test());
var myProd = new MyClass(() => new Prod());
Note that the Dart team is planning to add both class concept (.type) and reflection to the language.

What do you want actually do? Often people try to apply paradigms from some languages in some other languages which isn't the best way to do some things.

Since print is an instance method and not a static method, you don't need to pass a class itself to TestClass, just an instance of it. Your program can be fixed like so:
class MyClass {
String message = 'myClass';
void print() {
print(this.message);
}
}
class TestClass {
var myClass;
TestClass(MyClass myClass) {
this.myClass = myClass;
}
void debug() {
print('DEBUG: ');
this.myClass.print();
}
}
main() {
MyClass myClass = new MyClass();
testClass(myClass);
}
Or, more idiomatically:
class MyClass {
String message = 'myClass';
void print() => print(message);
}
class TestClass {
var myClass;
TestClass(this.myClass);
void debug() {
print('DEBUG: ');
myClass.print();
}
}
main() {
testClass(new MyClass());
}

Related

Autofac. How to get caller class Type?

Suppose we have two classes with same constructor Injectable dependency:
public class FirstClass
{
public FirstClass(ISomeDependency someDependency)
{ }
}
public class SecondClass
{
public SecondClass(ISomeDependency someDependency)
{ }
}
Now we have a registration for ISomeDependency:
builder.Register(x =>
{
string key = GetKeyFromCurrentHttpRequest();
// if "Caller" is "FirstClass" return new Dependency(key);
// else return new Dependency("defaultKey");
}).As<ISomeDependency>();
Note: This is a simplified use case. The real scenario is much more complicated.
1. How to get "Caller" type which tryies to resolve ISomeDependency?
2. Is there a better way design for such situations?
You can use delegate factories do achieve your goal. The only drawback is the FirstClass and SecondClass cannot use ISomeDependency as parameter.
You can try this code in a console application (just add Autofac dependency).
using System;
using Autofac;
namespace test
{
class MainClass
{
public static void Main(string[] args)
{
ContainerBuilder builder = new ContainerBuilder ();
builder.RegisterType<SomeDependency>().As<ISomeDependency>();
builder.RegisterType<FirstClass>();
builder.RegisterType<SecondClass>();
var container = builder.Build();
var dummy = container.Resolve<FirstClass>();
var dummy2 = container.Resolve<SecondClass>();
}
public interface ISomeDependency
{
}
public class SomeDependency : ISomeDependency
{
public delegate ISomeDependency Factory(string value);
private readonly string _value;
public SomeDependency(string value)
{
_value = value;
Console.WriteLine("Value = " + _value);
}
}
public class FirstClass
{
private ISomeDependency _dependency;
public FirstClass(SomeDependency.Factory factory)
{
_dependency = factory.Invoke("my value");
}
}
public class SecondClass
{
private ISomeDependency _dependency;
public SecondClass(SomeDependency.Factory factory)
{
_dependency = factory.Invoke("my value 2");
}
}
}
}

dart reflection call by String

I want to wrote method which call all function in class:
class Example extends MyAbstractClass {
void f1(){...}
void f2(){...}
void f3(){...}
Example(){
callAll();//this call f1(), f2() and f3().
}
}
I have problem in this part of code:
reflectClass(this.runtimeType).declarations.forEach((Symbol s, DeclarationMirror d) {
if (d.toString().startsWith("MethodMirror on ")) {
String methodName = d.toString().substring(16).replaceAll("'", "");
print(methodName);
// How to call function by name methodName?
}
});
instead of
if (d.toString().startsWith("MethodMirror on ")) {
you can use
if (d is MethodMirror) {
You need an InstanceMirror of an instance of the class. I think in your case this would be
var im = reflect(this).invoke(d.simpleName, []);
im.declarations.forEach((d) ...
see also How can I use Reflection (Mirrors) to access the method names in a Dart Class?
Using dson you can do:
library example_lib;
import 'package:dson/dson.dart';
part 'main.g.dart';
#serializable
class Example extends _$ExampleSerializable {
Example() {
_callAll();
}
fn1() => print('fn1');
fn2() => print('fn2');
fn3() => print('fn3');
fn4() => print('fn4');
_callAll() {
reflect(this).methods.forEach((name, method) {
if(name != '_callAll') this[name]();
});
}
}
main(List<String> arguments) {
_initMirrors();
new Example();
}

Unity - Multiple interface registration with a factory method to return same implementation

Consider I have the following types:
public interface IBaseInterface { }
public interface IInheritedInterface : IBaseInterface { }
public class MyClass : IInheritedInterface { }
//------------------------------------------------------------
public interface ISomeInterface { }
public class SomeClass : ISomeInterface {
private readonly IBaseInterface _myInterface;
public SomeClass(IBaseInterface myInterface) {
_myInterface = myInterface;
}
}
//------------------------------------------------------------
public interface ISomeOtherInterface { }
public class SomeOtherClass : ISomeOtherInterface {
private readonly IInheritedInterface _myInterface;
public SomeOtherClass(IInheritedInterface myInterface) {
_myInterface = myInterface;
}
//------------------------------------------------------------
So, what I am trying to achieve and wonder how could be done, if possible, is that whenever I construct either SomeClass or SomeOtherClass is to always get the same instance of MyClass. This example explains what I want:
var someClass = _container.Resolve<SomeClass>();
var someOtherClass = _container.Resolve<SomeOtherClass>();
// At this point, The following assert should pass
Assert.AreSame(someClass._myInterface, someOtherClass._myInterface)
Also note that MyClass needs to register using a factory method for other reasons. I have tried the following:
_container.RegisterType<IBaseInterface, MyClass>(
perRequestLifetime,
new InjectionFactory((c) =>
{ return FactoryMethod(c); }));
This will resolve SomeClass but will throw when trying to resolve SomeOtherClass since the container doesn't know how to construct IInheritedInterface.
I have also tried this:
_container.RegisterType<IBaseInterface, MyClass(
perRequestLifetime,
new InjectionFactory((c) => {
MyClass myClass;
// Construct object some how...
return myClass;
}));
_container.RegisterType<IInheritedInterface, MyClass(
perRequestLifetime,
new InjectionFactory((c) => {
return c.Resolve<IBaseInterface>() as MyClass;
}));
However, for some reason when I call Resolve() on both SomeClass and SomeOtherClass they both end up calling the factory of IInheritedInterface causing an endless loop! I then removed IBaseInterface registration and now resolving SomeClass throws.
Any ideas?
Thanks
Try this
container.RegisterType<IBaseInterface, MyClass>(new ContainerControlledLifetimeManager(), new InjectionFactory(ctr => new MyClass()));
container.RegisterType<IInheritedInterface, MyClass>();

How can refer base class instance?

The following example, how do I refer base class instance?
public class A
{
public string test;
public A()
{
B b = new B();
test = "I am A class of test.";
}
public void hello()
{
MessageBox.Show("I am A class of hello.");
}
class B
{
public B()
{
//Here...
//How can I get A class of test and call A class of hello method
//base.test or base.hello() are not working.
}
}
}
You'd have to pass a reference of A to B.
One way you can do this is as follows:
public class A
{
string name = "Class A";
public A()
{
var b = new B(this);
}
class B
{
public B(A a)
{
a.name.Dump(); // Write out the property of a.name to some stream.
}
}
}
To clearly distinguish between base class and nested class, please refer the example below.
namespace Example
{
class A
{
string Name = "test"; // access restricted only to this class
public string Type; // global access
internal string Access; // within defining namespace
protected string Code; // this class and subclass
// When you create a nested class like C, you can create instances of C within this class(A).
C c = new C();
class C
{
string name;
public C()
{
//this is a nested class and you cannot call A as its base
name = "test success";
}
}
}
class B : A
{
public string Type { get { return base.Type; } set { base.Type = value; } } // You can use base when you hide a base class member
public B()
{
Type = "test";
Code = "nothing";
Access = "success";
//Cannot Access 'Name' Here as it is private
}
}
}

Inline Interface implementation in Actionscript

Is something like this possible in Actionscript?
Java:
URLFetcherFactory.setCreator(
new IURLFetcherCreator() {
public IURLFetcher create() {
return new URLFetcher();
}
}
);
Actionscript:
?
I've been wondering about this and have been unable to find anything that indicates it's possible. Figured if it was possible, I'd be able to find an answer here. Thanks! Stackoverflow rocks!
You cannot create an instance of an interface. You can, however, create a factory class:
public class URLFetcherCreator : IURLFetcherCreator {
private var _cls : Class;
public URLFetcherCreator(Class cls) {
this._cls = cls;
}
public function create() : IURLFetcher
{
return new cls();
}
}
Alternatively, change setCreator to accept a Function that returns an IURLFetcher:
URLFetcherFactory.setCreator(
function() : IURLFetcher {
return new URLFetcher();
}
);
Try this:
URLFetcherFactory.setCreator(
new IURLFetcherCreator() {
public function create():IURLFetcher {
return new URLFetcher();
}
}
);
You can't use anonymous inner classes in AS3.
For special cases like callbacks you can use Function instead of anonymous inner classes.
Java:
interface Callback {
void done(String info);
}
class Service {
void process(Callback callback);
}
...
myService.process(new Callback() {
void done(String info) {
// trace(info);
}
}
AS3:
class Service {
public function process(callback:Function):void;
}
...
myService.process(function(info:String):void {
trace(info);
});

Resources