I use Realm dotnet. I wrote the generic class for any object.
It is my generic class.
public class Controller<T> where T : RealmObject, new()
{
private Realm realm;
public Controller()
{
this.realm = Realm.GetInstance();
}
public void Insert(T selfObj)
{
this.realm.Write(() =>
{
Debug.WriteLine(typeof(T)); // => "Country".
// ERROR: System.InvalidCastException has been thrown Specified cast is not valid.
var obj = this.realm.CreateObject<T>();
// TODO: write later.
}
}
}
And model class is here.
public class Country : RealmObject
{
public string Name { get; set; }
}
And, I called like this.
var cc = new Controller<Country>();
Country newCon = new Country()
{
Name = "Japan"
};
var newCon2 = new Country()
{
Name = "Korea"
};
cc.Insert(newCon);
The System.InvalidCastException has been thrown Specified cast is not valid.
error occurred.
My Controller
class already known T
is Country
object. Why realm.CreateObject<T>();
can't cast?
Could you tell me how to fix.
Update
The issue was resolved via email. The real class Country
descends from an intermediate Model
class which descends in turn from RealmObject
.
Currently we don't support inheritance in this manner. It is documented in our help .
We are probably going to move to using an interface instead of base class. There is a git issue discussing this .
Original
Firstly, I can't reproduce your exception with the current 0.76.1 release of Realm.
Using standalone objects like this works to a point. We don't yet support standalone objects which have relationships to other objects (see this IList issue ).
One minor change to your code sample. To pass a RealmObject
which is created standalone and copy it into a Realm, you can simply use Manage
. eg:
public class Controller<T> where T : RealmObject, new()
{
private Realm realm;
public Controller()
{
this.realm = Realm.GetInstance();
}
public void Insert(T selfObj)
{
this.realm.Write(() =>
{
Debug.WriteLine(typeof(T)); // => "Country".
this.realm.Manage<T>(selfObj);
}
); // closing paren was missing above too
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.