我在尝试构建一个应用程序时遇到了一个问题。问题是试图用一个通用的setField
函数设置SomeClass
中的字段。我的实现是这样的,但是遇到了this[fieldName]
的问题;
已编辑
class TestClass {
String name; // <- to set this the memberName = 'name';
int age; // <- to set this the memberName = 'age';
// and both will use the same setField as setter.
TestClass({required name, required age});
// the prev code is correct and no problem with it.
/** the use will be like this to set the value of name **/
/** test.setField(memberName : 'name', valueOfThatMemberName: 'test name'); // notice here **/
/** the use will be like this to set the value of age **/
/** test.setField(memberName : 'age', valueOfThatMemberName: 15); // notice here **/
void setField({required String memberName, required var valueOfThatMemberName}) {
// some extra validation and logic,..
this[memberName] = valueOfThatMemberName; // this gives this error:
/** Error: The operator '[]=' isn't defined for the class 'TestClass'. **/
}
// this will return the valueOfThePassedMemberName;
getField({required String memberName}) {
return this[memberName]; // <= this gives this error
/** Error: The getter 'memberName' isn't defined for the class 'TestClass'. **/
}
}
void main() {
TestClass test = TestClass(name: 'alaa', age: 14);
/** here is the way to use it. **/
test.setField(memberName: 'name', valueOfThePassedMemberName: 'test name'); // notice here
test.setField(memberName: 'age', valueOfThePassedMemberName: 16); // notice here
print(test.getField(memberName: 'name')); // <- this should print the name of test object.
}
只通过setField方法设置值。
添加可运行JS代码
// i need to do the exact same thing here with the dart.
export class Entity {
constructor(data: {}) {
Object.keys(data).forEach(key => {
this.set(key, data[key], true);
});
}
get(field: string) {
return this["_" + field];
}
set(field: string, value: any, initial = false) {
this["_" + field] = value;
}
}
1条答案
按热度按时间zf9nrax11#